2016-09-09 41 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') 
相关问题