代码之家  ›  专栏  ›  技术社区  ›  DrDee

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

  •  35
  • DrDee  · 技术社区  · 16 年前

    我试图让Oauth使用Python与GoogleAPI一起工作。我尝试了不同的oauth库,例如 oauth oauth2 和 djanog-oauth

    为了调试Oauth,我使用Google的 Oauth Playground 我研究过 API 和 Oauth documentation

    编辑:我最初的问题没有得到任何答案,所以我添加了我的代码。此代码不起作用的可能原因有两个:

    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
    
    6 回复  |  直到 16 年前
        1
  •  6
  •   sje397    16 年前

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

    http://github.com/sje397/Chess

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

    http://your-move.appspot.com

        2
  •  5
  •   pacifi30    14 年前

    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)
    
        3
  •  3
  •   Stephane JAIS    16 年前

    您尝试过官方的gdatapythonapi吗? 它随oauth客户端一起提供,并隐藏了oauth调用的复杂性。 http://code.google.com/p/gdata-python-client/

        4
  •  2
  •   AlBeebe    16 年前

    这可能就是答案。

    调用OAuthGetAccessToken时,您将使用consumer\u secret对base\u字符串进行签名,后跟一个&(符号)后接令牌_secret。

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

    http://hueniverse.com/2008/10/beginners-guide-to-oauth-part-iii-security-architecture/ 在明文和HMAC-SHA1方法中,共享密钥是使用者密钥和令牌密钥的组合。

        5
  •  2
  •   Yashh    16 年前

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

        6
  •  0
  •   Gabe    16 年前

    IIRC Google oauth不太符合标准,你知道吗 有