Python的urllib2/oauth2请求UbuntuOne文件API返回401未授权错误
我正在尝试发起一个基本的UbuntuOne API请求。
- 正如在这个链接上所解释的,我获取了OAUTH令牌,然后把它传递给UbuntuOne服务。
- 我顺利得到了令牌和消费者信息。
- 接下来,我尝试发起一个/api/file_storage/v1的API请求(可以参考这个链接)。请求是用OAUTH令牌进行签名的。
下面的代码片段就是我执行的代码(去掉了邮箱、密码和描述字段)。令牌和消费者数据都正确返回了。但是,当我发起/api/file_storage/v1请求时,服务器返回了'401 UNAUTHORIZED'的错误... 有人知道这是为什么吗?
import base64
import json
import urllib
import urllib2
import oauth2
email = 'bla'
password = 'foo'
description = 'bar'
class Unauthorized(Exception):
"""The provided email address and password were incorrect."""
def acquire_token(email_address, password, description):
"""Aquire an OAuth access token for the given user."""
# Issue a new access token for the user.
request = urllib2.Request(
'https://login.ubuntu.com/api/1.0/authentications?' +
urllib.urlencode({'ws.op': 'authenticate', 'token_name': description}))
request.add_header('Accept', 'application/json')
request.add_header('Authorization', 'Basic %s' % base64.b64encode('%s:%s' % (email_address, password)))
try:
response = urllib2.urlopen(request)
except urllib2.HTTPError, exc:
if exc.code == 401: # Unauthorized
raise Unauthorized("Bad email address or password")
else:
raise
data = json.load(response)
consumer = oauth2.Consumer(data['consumer_key'], data['consumer_secret'])
token = oauth2.Token(data['token'], data['token_secret'])
# Tell Ubuntu One about the new token.
get_tokens_url = ('https://one.ubuntu.com/oauth/sso-finished-so-get-tokens/')
oauth_request = oauth2.Request.from_consumer_and_token(consumer, token, 'GET', get_tokens_url)
oauth_request.sign_request(oauth2.SignatureMethod_PLAINTEXT(), consumer, token)
request = urllib2.Request(get_tokens_url)
for header, value in oauth_request.to_header().items():
request.add_header(header, value)
response = urllib2.urlopen(request)
return consumer, token
if __name__ == '__main__':
consumer, token = acquire_token(email, password, description)
print 'Consumer:', consumer
print 'Token:', token
url = 'https://one.ubuntu.com/api/file_storage/v1'
oauth_request = oauth2.Request.from_consumer_and_token(consumer, token, 'GET', url)
oauth_request.sign_request(oauth2.SignatureMethod_PLAINTEXT(), consumer, token)
request = urllib2.Request(url)
request.add_header('Accept', 'application/json')
for header, value in oauth_request.to_header().items():
request.add_header(header, value)
response = urllib2.urlopen(request)
1 个回答
1
问题出在“描述”这个字段上。它必须按照以下格式填写:
Ubuntu One @ $hostname [$application]
否则,UbuntuOne服务会返回“ok 0/1”,并且不会注册这个令牌。