【发布时间】:2021-10-16 06:22:01
【问题描述】:
我正在尝试让我的 google 身份验证在请求 Gmail 和日历数据的 Django 应用程序上工作。我已经在 Google 开发者控制台中设置了 oAuth API 并将它与我的项目链接起来,并且我已经三重检查了我的重定向 URI 是否与代码中的内容完全匹配(HTTP 与 HTTPS 没有错误,斜杠也没有任何不一致)。我确保我的密钥、密钥、ClientID 和 Client Secret 在我的 Django 应用程序的管理页面中都已配置且相同。我已经关注了许多 youtube 教程并搜索了有关堆栈溢出的其他问题,但身份验证仍然无法正常工作。我收到错误 400:redirect_uri_mismatch。尽管我已经检查了很多次以确认它们是相同的。
从所有教程中,我了解到这个错误有两个主要来源:
- 服务器端(可在云托管开发者控制台中修复)
- 客户端(可以通过更改代码来修复)
这两个错误都有自己的个性化消息,说明它是哪种类型的不匹配。
不过,我的说法是:您无法登录此应用,因为它不符合 Google 的 OAuth 2.0 政策。 \n\n如果您是应用开发者,请在 Google Cloud Console 中注册重定向 URI。
这是一张照片 Google Authentication error message
from django.shortcuts import render, redirect
from django.http import HttpRequest
from google_auth_oauthlib.flow import Flow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
from .models import CredentialsModel
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
import os
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '1'
#Scopes are what we should be allowed to access
SCOPES = ['https://mail.google.com/', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', 'openid']
"""
IF HAVING ISSUES WITH ANON USER:
Make sure you are on 127.0.0.1:8000, not localhost, both from the test-page and
the callback page. For some reason they are treated as different sessions and thus will have
issues maintaining a logged in user
"""
def oauth2callback(request):
activeUser = request.user
#URL is what we need to use for authentication
authorization_response = request.build_absolute_uri()
flow = Flow.from_client_secrets_file(
settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON,
scopes=SCOPES,
#This is where we are redirected after authentication
redirect_uri='http://127.0.0.1:8000/google/oauth2callback')
#Now get proper token
flow.fetch_token(authorization_response = authorization_response)
#print(request.user)
#Now save in our database
#print(flow.credentials)
try :
my_credential = CredentialsModel.objects.get(pk = activeUser)
except ObjectDoesNotExist:
CredentialsModel.objects.create(id = activeUser, credential = flow.credentials)
else:
my_credential.credential = flow.credentials
my_credential.save()
return redirect(flow.redirect_uri) #activeUser.get_absolute_url())
【问题讨论】:
-
尝试使用 Firefox 进行身份验证,看看您是否仍然遇到问题。我开始在一个浏览器中遇到问题,但在另一个浏览器中没有。
标签: python django google-authentication google-authenticator google-auth-library