2011-08-26 33 views
4

我正在將oAuth 1中的Python應用程序遷移到oAuth 2,該應用程序讀取用戶的Google日曆提要 。使用Python gdata和oAuth 2驗證日曆2

  • 通過OAuth 1: 我的應用程序會打開一個瀏覽器是用戶可以用他的GMail 帳戶進行身份驗證和授權訪問,和我的應用程序將獲得user_token, user_secret該用戶,然後驗證日曆飼料:

    client = gdata.calendar.client.CalendarClient(source='test') 
    client.auth_token = gdata.gauth.OAuthHmacToken(app_key, 
         app_secret,user_token,user_secret,gdata.gauth.ACCESS_TOKEN) 
    

由此看來,隱匿對將長期存在。

這是的access_token短暫的。

我玩了一下這裏的代碼http://codereview.appspot.com/4440067/ 並且工作正常。

我的問題:

-I我獲得的access_token,通過捲曲呼叫refresh_token從我 應用程序,我可以成功地同時檢索。然而,當我把它應用到 此代碼:

token = 
    gdata.gauth.OAuth2Token(client_id=client_id,client_secret=client_secret', 
          scope='https://www.google.com/calendar/ 
    feeds',user_agent='calendar-cmdline-sample/1.0') 
    uri = token.generate_authorize_url() 
    token.get_access_token(access_token) 

它給我:

Traceback (most recent call last): 
File "<stdin>", line 1, in <module> 
File "/Library/Python/2.6/site-packages/gdata/gauth.py", line 1267, 
in get_access_token 
    raise OAuth2AccessTokenError(error_msg) 
gdata.gauth.OAuth2AccessTokenError 

- 假設我能成功地做到上面,我可以保存訪問/刷新標記在DB。使用python gdata lib,我怎樣才能使用refresh_token來請求另一個access_token(因此在每次他們使用應用程序授權訪問時都不需要詢問用戶)

非常感謝!

中號

回答

1

Marchie,

我沒有看到你的堆棧跟蹤的其餘部分,但可以用,將解決你的整體問題,相應的解決方案給三個特別的問題。

問題I:值redirect_uri沒有設置在對象上。

注意如何請求的身體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 
    }) 

這依賴於redirect_uri財產被該對象最初在generate_authorize_url設置的值進行設置。因此,通過調用

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

重建令牌之後,你只需要簡單地設置重定向URI:

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

問題II:中redirect_uri默認值是不正確的(更具體,不建議使用) 。

由於您沒有參數調用generate_authorize_url,因此使用了redirect_uri的默認值,該值當前爲oob。由於OAuth 2.0 docs狀態,oob不在支持的值之中(它已被棄用)。

如果你確實使用已安裝的應用程序,你需要,而不是將其設置爲

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

此外,當你調用generate_authorize_url獲取初始令牌,你將需要使用這個作爲關鍵字參數

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

問題III:您正在使用不正確的值調用get_access_token(也一個還沒有在你的代碼片段被實例化)。

您應該使用授權後收到的代碼的字符串值或使用以'code'爲關鍵字的字典來調用此值。

這可以通過以下來完成:

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) 

後腳本:在patch的作者還使用了補丁發佈的blog post。 (請注意,在generate_authorize_url函數中使用關鍵字redirect_url而不是時,帖子中存在拼寫錯誤。)