Authenticating to Calendar with Python gdata and oAuth 2

ぐ巨炮叔叔 提交于 2019-12-04 11:31:20

Marchie,

I don't see the rest of your stack trace, but can give three particular issues with corresponding solutions that will solve your overall problem.

Problem I: The value redirect_uri is not set on the object.

Note how the body of the request is specified in get_access_token:

body = urllib.urlencode({
  'grant_type': 'authorization_code',
  'client_id': self.client_id,
  'client_secret': self.client_secret,
  'code': code,
  'redirect_uri': self.redirect_uri,
  'scope': self.scope
  })

This depends on the redirect_uri property being set on the object to the value that was originally set in generate_authorize_url. So, after reconstructing the token by calling

token = gdata.gauth.OAuth2Token(...)

you will simply need to set the redirect URI:

token.redirect_uri = 'http://path/that/you/set'

Problem II: The default value of redirect_uri is incorrect (more specifically, deprecated).

Since you called generate_authorize_url with no arguments, the default value for redirect_uri was used, which is currently oob. As the OAuth 2.0 docs state, the oob is not among the supported values (it has been deprecated).

If you are indeed using an Installed Application, you will need to instead set it to

token.redirect_uri = 'urn:ietf:wg:oauth:2.0:oob'

In addition, when you call generate_authorize_url to get the initial token, you will need to use this as a keyword parameter

url = token.generate_authorize_url(redirect_uri='urn:ietf:wg:oauth:2.0:oob')

Problem III: You are calling get_access_token with the incorrect value (also one that hasn't been instantiated in your code snippet).

You should either call this with a string value of the code you receive after authorizing or with a dictionary that has 'code' as a key.

This can be done via the following:

import atom.http_core

# Page the user is redirected to after authorizing
redirected_page = 'http://path/that/you/set?code=RANDOM-CODE'
uri = atom.http_core.ParseUri(redirected_page)

# uri.query is a dictionary with the query string as key, value pairs
token.get_access_token(uri.query)

Post Script: The author of the patch also published a blog post on using the patch. (Note there is a typo in the post when the keyword redirect_url is used instead of redirect_uri in the generate_authorize_url function.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!