使用 Python / Django 的 Google API 示例的 Oauth
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2282924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Oauth for Google API example using Python / Django
提问by DrDee
I am trying to get Oauth working with the Google API using Python. I have tried different oauth libraries such as oauth, oauth2and djanog-oauthbut I cannot get it to work (including the provided examples).
我正在尝试使用 Python 使 Oauth 与 Google API 一起工作。我尝试了不同的 oauth 库,例如oauth、oauth2和djanog-oauth但我无法让它工作(包括提供的示例)。
For debugging Oauth I use Google's Oauth Playgroundand I have studied the APIand the Oauth documentation
为了调试 Oauth,我使用 Google 的Oauth Playground并且我研究了API和Oauth 文档
With some libraries I am struggling with getting a right signature, with other libraries I am struggling with converting the request token to an authorized token. What would really help me if someone can show me a working example for the Google API using one of the above-mentioned libraries.
对于某些库,我正在努力获得正确的签名,而对于其他库,我正在努力将请求令牌转换为授权令牌。如果有人可以使用上述库之一向我展示 Google API 的工作示例,这对我有什么真正的帮助。
EDIT: My initial question did not lead to any answers so I have added my code. There are two possible causes of this code not working:
1) Google does not authorize my request token, but not quite sure how to detect this
2) THe signature for the access token is invalid but then I would like to know which oauth parameters Google is expecting as I am able to generate a proper signature in the first phase.
编辑:我最初的问题没有得到任何答案,所以我添加了我的代码。这段代码不工作有两个可能的原因:
1)谷歌没有授权我的请求令牌,但不太确定如何检测这个
2)访问令牌的签名无效,但我想知道谷歌的 oauth 参数期待,因为我能够在第一阶段生成正确的签名。
This is written using oauth2.py and for Django hence the HttpResponseRedirect.
这是使用 oauth2.py 和 Django 编写的,因此是 HttpResponseRedirect。
REQUEST_TOKEN_URL = 'https://www.google.com/accounts/OAuthGetRequestToken'
AUTHORIZATION_URL = 'https://www.google.com/accounts/OAuthAuthorizeToken'
ACCESS_TOKEN_URL = 'https://www.google.com/accounts/OAuthGetAccessToken'
CALLBACK = 'http://localhost:8000/mappr/mappr/oauth/' #will become real server when deployed
OAUTH_CONSUMER_KEY = 'anonymous'
OAUTH_CONSUMER_SECRET = 'anonymous'
signature_method = oauth.SignatureMethod_HMAC_SHA1()
consumer = oauth.Consumer(key=OAUTH_CONSUMER_KEY, secret=OAUTH_CONSUMER_SECRET)
client = oauth.Client(consumer)
request_token = oauth.Token('','') #hackish way to be able to access the token in different functions, I know this is bad, but I just want it to get working in the first place :)
def authorize(request):
if request.GET == {}:
tokens = OAuthGetRequestToken()
return HttpResponseRedirect(AUTHORIZATION_URL + '?' + tokens)
elif request.GET['oauth_verifier'] != '':
oauth_token = request.GET['oauth_token']
oauth_verifier = request.GET['oauth_verifier']
OAuthAuthorizeToken(oauth_token)
OAuthGetAccessToken(oauth_token, oauth_verifier)
#I need to add a Django return object but I am still debugging other phases.
def OAuthGetRequestToken():
print '*** OUTPUT OAuthGetRequestToken ***'
params = {
'oauth_consumer_key': OAUTH_CONSUMER_KEY,
'oauth_nonce': oauth.generate_nonce(),
'oauth_signature_method': 'HMAC-SHA1',
'oauth_timestamp': int(time.time()), #The timestamp should be expressed in number of seconds after January 1, 1970 00:00:00 GMT.
'scope': 'https://www.google.com/analytics/feeds/',
'oauth_callback': CALLBACK,
'oauth_version': '1.0'
}
# Sign the request.
req = oauth.Request(method="GET", url=REQUEST_TOKEN_URL, parameters=params)
req.sign_request(signature_method, consumer, None)
tokens =client.request(req.to_url())[1]
params = ConvertURLParamstoDictionary(tokens)
request_token.key = params['oauth_token']
request_token.secret = params['oauth_token_secret']
return tokens
def OAuthAuthorizeToken(oauth_token):
print '*** OUTPUT OAuthAuthorizeToken ***'
params ={
'oauth_token' :oauth_token,
'hd': 'default'
}
req = oauth.Request(method="GET", url=AUTHORIZATION_URL, parameters=params)
req.sign_request(signature_method, consumer, request_token)
response =client.request(req.to_url())
print response #for debugging purposes
def OAuthGetAccessToken(oauth_token, oauth_verifier):
print '*** OUTPUT OAuthGetAccessToken ***'
params = {
'oauth_consumer_key': OAUTH_CONSUMER_KEY,
'oauth_token': oauth_token,
'oauth_verifier': oauth_verifier,
'oauth_token_secret': request_token.secret,
'oauth_signature_method': 'HMAC-SHA1',
'oauth_timestamp': int(time.time()),
'oauth_nonce': oauth.generate_nonce(),
'oauth_version': '1.0',
}
req = oauth.Request(method="GET", url=ACCESS_TOKEN_URL, parameters=params)
req.sign_request(signature_method, consumer, request_token)
response =client.request(req.to_url())
print response
return req
def ConvertURLParamstoDictionary(tokens):
params = {}
tokens = tokens.split('&')
for token in tokens:
token = token.split('=')
params[token[0]] = token[1]
return params
采纳答案by sje397
I have OAuth working in a python App Engine app:
我有 OAuth 在 python App Engine 应用程序中工作:
http://github.com/sje397/Chess
http://github.com/sje397/Chess
The app is running at:
该应用程序正在运行:
回答by pacifi30
This work for me.
这对我有用。
def login(request):
consumer_key = 'blabla'
consumer_secret = 'blabla'
callback = request.GET['callback']
request_token_url = 'https://api.linkedin.com/uas/oauth/requestToken'
authorize_url = 'https://api.linkedin.com/uas/oauth/authorize'
access_token_url = 'https://api.linkedin.com/uas/oauth/accessToken'
consumer = oauth.Consumer(consumer_key, consumer_secret)
if ('oauth_verifier' not in request.GET):
client = oauth.Client(consumer)
body = 'oauth_callback=http://shofin.com/login?callback='+callback+"&placeId="+request.GET[placeId]
resp,content = client.request(request_token_url,"POST",headers={'Content-Type':'application/x-www-form-urlencoded'},body=body)
request_token = dict(urlparse.parse_qsl(content))
loginUrl = authorize_url+"?oauth_token="+request_token['oauth_token']
cache.set(request_token['oauth_token'],request_token['oauth_token_secret'])
return HttpResponseRedirect(loginUrl)
elif request.GET['oauth_verifier']:
token = oauth.Token(request.GET['oauth_token'],cache.get(request.GET['oauth_token']))
token.set_verifier(request.GET['oauth_verifier'])
client = oauth.Client(consumer, token)
resp,content = client.request(access_token_url,"POST",{})
access_token = dict(urlparse.parse_qsl(content))
token = oauth.Token(key=access_token['oauth_token'], secret=access_token['oauth_token_secret'])
client = oauth.Client(consumer, token)
resp,json = client.request("http://api.linkedin.com/v1/people/~?format=json")
return render_to_response(callback,{'placeId':request.GET['placeId'],'userId':userId,'folkId':folkId)
回答by Stephane JAIS
Have you tried the official gdata python api ? It ships with an oauth client and hides the complexity of oauth calls. http://code.google.com/p/gdata-python-client/
你试过官方的 gdata python api 吗?它附带一个 oauth 客户端并隐藏了 oauth 调用的复杂性。 http://code.google.com/p/gdata-python-client/
回答by AlBeebe
This may be the answer.
这可能就是答案。
When calling OAuthGetRequestToken you sign the base_string with your consumer_secret followed by an & (ampersand)
调用 OAuthGetRequestToken 时,您使用您的 consumer_secret 后跟 &(与号)对 base_string 进行签名
When calling OAuthGetAccessToken you sign the base_string with your consumer_secret followed by an & (ampersand) followed by token_secret.
调用 OAuthGetAccessToken 时,您使用 consumer_secret 后跟一个 &(与号)和 token_secret 对 base_string 进行签名。
You would sign the base_string using (consumer_secret + "&") for OAuthGetRequestToken and you would sign the base_string using (consumer_secret + "&" + token_secret) for OAuthGetAccessToken
您将使用 (consumer_secret + "&") 为 OAuthGetRequestToken 签名 base_string,您将使用 (consumer_secret + "&" + token_secret) 为 OAuthGetAccessToken 签名 base_string
http://hueniverse.com/2008/10/beginners-guide-to-oauth-part-iii-security-architecture/In the PLAINTEXT and HMAC-SHA1 methods, the shared secret is the combination of the Consumer Secret and Token Secret.
http://hueniverse.com/2008/10/beginners-guide-to-oauth-part-iii-security-architecture/在PLAINTEXT和HMAC-SHA1方法中,共享的secret是Consumer Secret和Token Secret的组合.
回答by Yashh
Tornado has working code for Google oauth. Check it out here. google auth. I 've used it and worked pretty well out of the box. All you need to do is pluck out the class and carefully put it into a django view.
Tornado 有适用于 Google oauth 的工作代码。在这里查看。谷歌授权。我已经使用过它并且开箱即用。您需要做的就是取出类并小心地将其放入 django 视图中。
PS: Tornado makes use of async module for the user to return. Since you are using django you need to rely on some get variable to identify that a user has just granted access to your application.
PS:Tornado 使用 async 模块让用户返回。由于您使用的是 django,您需要依靠一些 get 变量来识别用户刚刚授予对您的应用程序的访问权限。
回答by Gabe
IIRC Google oauth is not quite following the standard, you haveto specify what service you're requesting for (look at the examples provided in the google docs) in the request as an additional parameter, or it won't work.
IIRC Google oauth 不太符合标准,您必须在请求中指定您请求的服务(查看 google 文档中提供的示例)作为附加参数,否则将无法工作。