【问题标题】:How to generate oauth signature with hmac-sha1 with python?如何使用 python 使用 hmac-sha1 生成 oauth 签名?
【发布时间】:2019-11-01 13:56:32
【问题描述】:

我正在尝试使用 Python 从 REST API 中获取信息,它需要 OAuth 标识。我已经设法用 Postman 编写请求并且它有效。但是 Postman 给我的 python 代码不起作用:

import requests

url = "https://www.somewebsite.com/api/rest/products/store/2"

querystring = {"limit":"100","page":"5"}

headers = {
    'Authorization': "OAuth oauth_consumer_key="3626311748bcf2072da2bd475fccfa3c",\
oauth_token="878c7c0eb6122e6208b75e2ba9e23f86",\
oauth_signature_method="HMAC-SHA1",oauth_timestamp="1560892926",\
oauth_nonce="9Cy9wmOo21v",oauth_signature="9VqTR2qFQLZ%2Fz2Ibvny1e%2BC7Zes%3D"",
    'User-Agent': "PostmanRuntime/7.15.0",
    'Accept': "*/*",
    'Cache-Control': "no-cache",
    'Postman-Token': "eef345cc-52ee-4496-8109-e7ea013adb9c,0834423c-041c-4ca5-8bef-33876c311ef6",
    'Host': "www.inart.com",
    'cookie': "PHPSESSID=gmjmllng429gfk8t0hvd1abbu3",
    'accept-encoding': "gzip, deflate",
    'Connection': "keep-alive",
    'cache-control': "no-cache"
    }

response = requests.request("GET", url, headers=headers, params=querystring)

print(response.text)

不工作的部分当然是nonce、时间戳和签名。我制作了一个生成随机随机数和随机时间戳的函数,但我不知道如何为 HMAC-SHA1 生成有效签名。 是否有一个库可以为我进行身份验证,还是我需要编写自己的函数来生成有效签名?签名是依赖于整个调用还是仅仅依赖于 nonce 和 timestamp 和 tokens 之类的部分? 任何帮助将不胜感激!

【问题讨论】:

    标签: python oauth python-requests


    【解决方案1】:

    你可以查看这个库

    https://requests-oauthlib.readthedocs.io/en/latest/

    它同时支持 Oauth1 和 Oauth2,并提供大量文档。无需担心创建随机数、时间戳以及 oauth_signature。只需提供您的 app_key、app_secret、request_token_url、authorization_url 和 access_token_url。

    【讨论】:

      【解决方案2】:

      您可以使用这种方法同时使用 oauth2 Libary 和 Request,我更喜欢将 ouath2 与 Authorization: Bearer Token 一起使用。 但是,OAuth 1.0 需要加密实现和加密互操作性。虽然安全,但对于许多开发人员来说实施起来是一个挑战。

      OAuth 2.0 定义了四个角色(客户端、授权服务器、资源服务器和资源所有者),OAuth 1 对这些角色使用了一组不同的术语。 OAuth 2.0“客户端”被称为“消费者”,“资源所有者”被简称为“用户”,“资源服务器”被称为“服务提供者”。 OAuth 1 也没有明确区分资源服务器和授权服务器的角色。

      params = {
                  "oauth_version": "1.0",
                  "oauth_nonce": oauth2.generate_nonce(),
                  "oauth_timestamp": str(oauth2.generate_timestamp()),
                  "oauth_token": token.key,
                  "oauth_consumer_key": consumer.key
              }
              req = oauth2.Request(method="GET", url=url, parameters=params)
      
              signature_method = oauth2.SignatureMethod_HMAC_SHA1()
              req.sign_request(signature_method, consumer, token)
              headers = req.to_header()
      
      payload = {}
      
      response = requests.request("GET", url, headers=headers, data=payload)
      
      print(response.text)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-25
        • 2011-05-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-21
        • 2017-07-08
        • 1970-01-01
        相关资源
        最近更新 更多