2016-09-09 46 views
1

我的(Django)應用程序要求用戶使用Google帳戶登錄。該應用程序的一項功能還是通過Gmail API發送電子郵件。如何爲應用程序google登錄和登錄gmail設置憑據

到目前爲止,我已經設置了一個類型爲Web application的憑證,該憑證可用於登錄(最後一行)。

enter image description here

電子郵件發送,因爲一步

2016-09-09 05:30:53,535 :Starting new HTTPS connection (1): accounts.google.com 
2016-09-09 05:30:53,779 :Starting new HTTPS connection (1): www.googleapis.com 

停止上述消息使我懷疑,我有不正確的憑據不與該作品(「的Web應用程序」)的憑證。我的問題是:

我需要在谷歌控制檯中設置兩組憑證(因此有兩個client_secret.json文件),一個用於登錄,一個用於通過Gmail API發送電子郵件?或者,我是否通過一些神祕的魔法誦讀將登錄和Gmail-API身份驗證掛接到一個憑證?任何信息非常感謝。

+0

客戶端ID訪問您在啓用API部分啓用了所有的API。只要用戶使用範圍電子郵件進行身份驗證(我認爲這是一個或者gmail),您可以使用相同的客戶端ID來訪問許多API。它的認證範圍決定了你可以訪問什麼。上面的消息並沒有告訴我很多。讓我們看看YouTube的視頻唄:) – DaImTo

+0

@DaImTo目前我唯一定義的範圍是[''https://www.googleapis.com/auth/gmail.send''](https://developers.google.com/Gmail的/ API/AUTH /範圍)。我沒有看到(請參閱上一個鏈接),我可以在其中添加「登錄」範圍。希望看到youtube視頻自己。編輯:哼,也許[這](https://developers.google.com/identity/protocols/googlescopes),特別是在谷歌登錄下的'profile'和'login'? –

+0

它已經有一段時間了,但我認爲登錄去通過加https://developers.google.com/+/web/api/rest/oauth btw gmail是一個痛苦的只是說,我不是一個蟒蛇人只是試圖指出你在正確的方向 – DaImTo

回答

1

通過python-social-auth在Django中添加其他範圍不是開箱即用,但也不難(two ways described here)。我選擇了第一個選項並覆蓋了get_scope方法。

views.py,我成立了

flow = client.flow_from_clientsecrets(
    CLIENT_SECRET_FILE, 
    scope=SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPES, 
    redirect_uri='https://yourdomain.com/callbacklinkforgmail') 

redirect_uri應該與谷歌控制檯重定向的URL。

請求權限是根據存儲在某處的憑證完成的。在我的情況下,一個模型。

# model with variable/column 'credentials' 
storage = Storage(YourModel, 'id', request.user, 'credentials') 
      credential = storage.get() 
      if credential is None or credential.invalid is True: 
       flow.params['state'] = xsrfutil.generate_token(SOCIAL_AUTH_GOOGLE_OAUTH2_KEY, 
                   request.user) 
       authorize_url = flow.step1_get_authorize_url() 
       return HttpResponseRedirect(authorize_url) 
      else: 
       http = credential.authorize(httplib2.Http()) 
       service = discovery.build('gmail', 'v1', http=http) 

當這一步驟完成後,重定向redirect_uri到這證實了匹配的功能。在我的情況下,這是在views.py

@login_required 
def auth_return(request): 
    if not xsrfutil.validate_token(SOCIAL_AUTH_GOOGLE_OAUTH2_KEY, request.GET['state'].encode('utf-8'), request.user): 
     return HttpResponseBadRequest() 

    credential = flow.step2_exchange(request.GET) 
    storage = Storage(YourModel, 'id', request.user, 'credentials') 
    storage.put(credential) 
    return HttpResponseRedirect("/") 

,並進入我的應用程序的urls.py

url(r'^callbacklinkforgmail/$', views.auth_return, name='mailsend') 
相關問題