Oauth用于使用Python/Django的Google API示例

Oauth用于使用Python/Django的Google API示例,python,django,oauth,google-api,Python,Django,Oauth,Google Api,我试图让Oauth使用Python与GoogleAPI一起工作。我已经尝试了不同的oauth库,例如,和,但是我无法让它工作(包括提供的示例) 为了调试Oauth,我使用了Google,并且我研究了 对于某些库,我正在努力获得正确的签名,对于其他库,我正在努力将请求令牌转换为授权令牌。如果有人能向我展示一个使用上述库之一的GoogleAPI的工作示例,那会对我有什么真正的帮助呢 编辑:我最初的问题没有得到任何答案,所以我添加了我的代码。此代码不工作有两种可能的原因: 1) 谷歌没有授权我的请求令

我试图让Oauth使用Python与GoogleAPI一起工作。我已经尝试了不同的oauth库,例如,和,但是我无法让它工作(包括提供的示例)

为了调试Oauth,我使用了Google,并且我研究了

对于某些库,我正在努力获得正确的签名,对于其他库,我正在努力将请求令牌转换为授权令牌。如果有人能向我展示一个使用上述库之一的GoogleAPI的工作示例,那会对我有什么真正的帮助呢

编辑:我最初的问题没有得到任何答案,所以我添加了我的代码。此代码不工作有两种可能的原因:
1) 谷歌没有授权我的请求令牌,但不太确定如何检测此
2) 访问令牌的签名无效,但是我想知道Google期望的oauth参数是什么,因为我能够在第一阶段生成正确的签名

这是使用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

这可能就是答案

调用OAuthGetRequestToken时,使用使用者密钥对基本字符串进行签名,后跟一个&(符号和)

调用OAuthGetAccessToken时,您使用consumer\u secret对基本\u字符串进行签名,后跟一个&(与符号),后跟token\u secret

您可以使用(consumer_secret+“&”)为OAuthGetRequestToken和 您可以使用(consumer\u secret+“&”+令牌\u secret)为OAuthGetAccessToken对基本字符串进行签名

在明文和HMAC-SHA1方法中,共享密钥是使用者密钥和令牌密钥的组合


您尝试过官方的gdatapythonapi吗? 它随oauth客户端一起提供,并隐藏了oauth调用的复杂性。

IIRC Google oauth没有完全遵循标准,您必须在请求中指定您请求的服务(查看Google文档中提供的示例)作为附加参数,否则它将不起作用。

Tornado有Google oauth的工作代码。在这里查看。我已经用过了,而且在开箱即用的情况下效果很好。你所需要做的就是把这个类取出,仔细地放到django视图中


PS:Tornado使用异步模块让用户返回。由于您使用的是django,您需要依赖一些get变量来标识用户刚刚授予了对您的应用程序的访问权限。

我让OAuth在python应用程序引擎应用程序中工作:

应用程序正在以下位置运行:

这是我的工作

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)

此示例仅使用Google+API后端代码,还是混合使用客户端和后端代码?