OAuth1.0的在http请求中的使用方式以及签名算法说明

发布时间 2023-11-13 20:21:51作者: 冯亮

1、在http request header的Authorization中,其格式为Authorization: "OAuth oauth_consumer_key="OAuth Consume Key",oauth_token="OAuth Token",oauth_signature_method="HMAC-SHA256",oauth_timestamp="OAuth Timestamp",oauth_nonce="OAuth Nonce String",oauth_version="1.0",oauth_signature="OAuth Signature""

 

2、oauth_consumer_key应该存储在服务器上

 

3、oauth_token应该存储在服务器上

 

4、oauth_signature_method为oauth_signature的签名方法,具体的签名方法实现,参考具体语言。PHP使用的是hash_hmac('sha256', $signatureString, $signatureKey, true)

 

5、oauth_timestamp是当前时间的时间戳

 

6、oauth_nonce是随机字符串

 

7、oauth_signature签名的实现原理是:

(1)拼接http请求大写的方法,例如:HEAD, GET , POST。假设此步骤形成的字符串为httpMethod

 

(2)对请求的URL中的Base String进行URL encode。假设URL是https://api.mg.dev.baby-go.com/rest/V1/categories/5/products?a=1&b=2,那么base URL则为https://api.mg.dev.baby-go.com/rest/V1/categories/5/products,并用步骤(1)中的httpMethod和次步骤中的字符串baseString拼接成string1。PHP中的URL encode方法为:rawurlencode

 

 

(3)将Authorization OAuth后面的键值对,按照键根据ASCII从小到大排序。PHP使用ksort,其他语言参考其具体实现。排序后的字符串用&连接,并用步骤(2)中的string1和次步骤中的字符串拼接成signatureString

 

(4)签名key。签名key由Magento Integration中的Consumer Secret和Access Token Secret,用&拼接成signatureKey

 

(5)签名。签名使用的方法在oauth_signature_method设置,本案例中使用的是HMAC-SHA256,具体的实现参考使用语言。PHP使用的是hash_hmac('sha256', $signatureString, $signatureKey, true);

 

(6)经过HMAC-SHA256签名后的结果如果是二进制数据,需要使用base64 encode

Reference Doc: https://oauth.net/core/1.0/#anchor14