1

我正在尝试发出一个基本的 UbuntuOne API 调用。

  1. 正如https://one.ubuntu.com/developer/account_admin/auth/otherplatforms上所解释的,我正在获取 OAUTH 令牌,然后将其传递给 UbuntuOne 服务。
  2. 我可以得到令牌和消费者信息
  3. 然后我尝试发出 /api/file_storage/v1 API 调用(请参阅:https://one.ubuntu.com/developer/files/store_files/cloud。)使用 OAUTH 令牌对请求进行签名。

下面的代码片段是我正在执行的确切代码(减去 email.password/description 字段。)正确返回了令牌和消费者数据。发出 /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)
4

1 回答 1

1

问题在于“描述”字段。它必须采用以下格式:

Ubuntu One @ $hostname [$application]

否则,UbuntuOne 服务会返回“ok 0/1”并且不注册令牌。

于 2013-01-26T21:11:32.800 回答