在Django中实现Google注册

时间:2019-05-24 06:35:04

标签: python django python-3.x google-authentication

我想使用Google建议的库(例如oauthclient)在我的Web应用程序中实现Google注册。 我希望我的用户通过Google进行身份验证并登录。 这是我的views.py:

FLOW = flow_from_clientsecrets(
    settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON,
    scope='profile email',#enter your required scope
    redirect_uri='http://127.0.0.1:8000/home',
    prompt='consent')

def gmail_authenticate(request):
    storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential')
    credential = storage.get() #credential of the user
    if credential is None or credential.invalid:
        #credential is not present or invalid
        #so, generating credential
        FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY,
                                                       request.user)
        authorize_url = FLOW.step1_get_authorize_url()
        return HttpResponseRedirect(authorize_url)
    else:
        #if credential is present and valid
        http = httplib2.Http()
        http = credential.authorize(http)
        service = build('gmail', 'v2', http=http)
        print('access_token = ', credential.access_token)
        status = True
        return render(request, 'index.html', {'status': status})

def auth_return(request):
    get_state = bytes(request.GET.get('state'), 'utf8')
    if not xsrfutil.validate_token(settings.SECRET_KEY, get_state,
                                   request.user):
        return HttpResponseBadRequest()
    #storing credential to DB
    credential = FLOW.step2_exchange(request.GET.get('code'))
    storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential')
    storage.put(credential)
    print("access_token: %s" % credential.access_token)
    return HttpResponseRedirect("/")

DjangoORMStorage类需要用户实例,但是我不想在用户验证我的Google之前创建User。帮助我更改代码和流程。

1 个答案:

答案 0 :(得分:1)

只需一个简单的Google搜索即可返回大量相关结果:

  1. How to Add Social Login to Django
  2. How to add Google and Github OAuth in Django
  3. OAuth Authentication in Django with social-auth
  4. Adding Social Authentication to Django

基本上,将Python Social Auth库添加到您的项目并将其配置为支持Google。