关于Oauth1.0认证及认证后调用API的方法

假设已经拿到以下 consumer_key:

{
        'consumer_key':  '79a7578ce6cf4a6fa27dbf30c6324df4',
        'consumer_secret': 'c7ed87c12e784e48983e3bcdc6889dad'
}

并且拿到用户的授权,得到以下 oauth_token:

{
        'oauth_token':'fa361a4a1dfc4a739869020e586582f9',
        'oauth_token_secret':'0183ce137e4d4170b2ac19d3a9fda677'
}

假设服务器地址为 openapi.kuaipan.cn,现在需要向 http://openapi.kuaipan.cn/1/fileops/create_folder 用GET方法发出请求,请求参数 (parameters) 如下:

{
        'oauth_version': '1.0', 
        'oauth_token': 'fa361a4a1dfc4a739869020e586582f9', 
        'oauth_signature_method': 'HMAC-SHA1', 
        'oauth_nonce': '58456623', 
        'oauth_timestamp': 1328881571, 
        'oauth_consumer_key': '79a7578ce6cf4a6fa27dbf30c6324df4', 
        'path': '/test@kingsoft.com', 
        'root': 'kuaipan'
}

首先计算字符基串 (base string),参考算法(伪代码)可以为:

http_method + "&" +
url_encode( base_uri ) + "&" +
url_encode(
        “&”.join(
                sort( [url_encode ( k ) + "=" +url_encode ( v ) for k, v in paramesters.items() ]
        )
)

注意点:

  1. http_method只能为大写,本例子中是GET;
  2. base_uri是不包括 "?" 号和其右边的query参数的uri,本例中是http://openapi.kuaipan.cn/1/fileops/create_folder ,传输协议,主机地址必须用小写,请不要包含端口号,请求路径也是大小写区分;
  3. 参数(parameters)按照其参数名的字典序排序,本例子的顺序是[oauth_consumer_key, oauth_nonce, oauth_signature_method, oauth_timestamp, oauth_token, oauth_version, path, root];
  4. urlencode编码的字符需要用utf8转编码,16进制部分需要大写,如等号”=”是%3D而不是%3d;
  5. urlencode规则:只有字母数字和[.-_~](红色部分,不包括方括号)不用encode,其他字符都需要,例如urlencode(".-_~+*")=".-_~%20%2B%2A"

这样我们根据算法生成字符基串如下(注意蓝色部分是%2540而不是%40):

GET&http%3A%2F%2Fopenapi.kuaipan.cn%2F1%2Ffileops%2Fcreate_folder&oauth_consumer_key%3D79a7578ce6cf4a6fa27
dbf30c6324df4%26oauth_nonce%3D58456623%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1328881571
%26oauth_token%3Dfa361a4a1dfc4a739869020e586582f9%26oauth_version%3D1.0%26path%3D%252Ftest%2540kingsoft.com
%26root%3Dkuaipan

然后生成签名加密的密钥(记得有个&),注意假如没有oauth_token的话,蓝色部分是不用包含的:

c7ed87c12e784e48983e3bcdc6889dad&0183ce137e4d4170b2ac19d3a9fda677

假如没有oauth_token的话,密钥为 c7ed87c12e784e48983e3bcdc6889dad&,在本例子中,有oauth_token。

使用密钥通过HMAC-SHA1算法签名字符基串,生成签名(先生成数字签名,然后再用base64 encode):

pa7Fuh9GQnsPc+Lcn+Qu6G7LVEU=

最后把urlencode后的签名作为oauth_signature的值,向连接发出请求:

curl –k 
"http://openapi.kuaipan.cn/1/fileops/create_folder?oauth_version=1.0&oauth_signature=pa7Fuh9GQnsPc%2BLcn
%2BQu6G7LVEU%3D&oauth_token=fa361a4a1dfc4a739869020e586582f9&oauth_signature_method=HMAC-SHA1&oauth_nonc
e=58456623&oauth_timestamp=1328881571&path=%2Ftest%40kingsoft.com&oauth_consumer_key=79a7578ce6cf4a6fa27
dbf30c6324df4&root=kuaipan"
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值