Google+登录服务器端应用,为访问令牌交换验证码

时间:2014-02-26 20:18:03

标签: oauth-2.0 google-plus google-oauth

我正在尝试按照此流程使用python服务器后端在Android应用程序上登录用户:

https://developers.google.com/+/web/signin/server-side-flow

我成功从Android应用程序获取授权代码,但是当我尝试从服务器交换此代码以获取访问令牌时,我收到“invalid_request”错误。

在Android应用中,我使用与服务器上相同的client_id,该服务器位于我的控制台的“Web应用程序的客户端ID”下。我已经验证了redirect_uri是正确的。是否无法从Android客户端生成授权代码并使用服务器来交换访问令牌?

我的python代码是:

def auth_params(self):
  client_id, client_secret = self.get_key_and_secret()
  return {
      'grant_type': 'authorization_code',    
      'code': self.data.get('code', ''),  # auth code from app
      'client_id': client_id,
      'client_secret': client_secret,
      'redirect_uri': self.get_redirect_uri()
  }       

@classmethod
def auth_headers(cls):
    return {'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'}

def auth_complete(self, *args, **kwargs):
  params = self.auth_params()
  request = Request('https://accounts.google.com/o/oauth2/token', data=urlencode(params),
                    headers=self.auth_headers())
  try:
      response = simplejson.loads(urlopen(request).read())
  except HTTPError, e:
      print 'fml'

1 个答案:

答案 0 :(得分:3)

有两个特殊的重定向URI实际上没有重定向回服务器:“postmessage”和“urn:ietf:wg:oauth:2.0:oob”。这些特殊的重定向URI不会触发重定向POST到您的服务器,而是在响应请求时返回OAuth 2.0令牌。

当您交换访问令牌和刷新令牌的代码时,与授权码相关联的重定向URI需要匹配。

由于您的授权码来自Android设备,因此您的重定向URI可能在此行上不匹配:

  'redirect_uri': self.get_redirect_uri()

对于Android代码交换,重定向URI必须为:  urn:ietf:wg:oauth:2.0:oob

希望这会有所帮助。您可能已经注意到,如果您还要从Web登录或Android返回授权代码,则需要适当设置重定向URI(例如,针对Android的urn [...],'postmessage'或已配置否则重定向。)