我试图让我的谷歌认证工作在Django应用程序,是要求Gmail和日历数据。我已经在Google控制台中设置了oAuth API并将其与我的项目链接,并且我已经三次检查我的重定向URI是否与代码中的URI完全匹配(HTTPvs.HTTPS没有错误,也没有任何与斜杠不一致的地方)。我确保我的密钥、秘密密钥、ClientID和客户端秘密都在我的Django应用程序的管理页面中配置和相同。我已经跟踪了许多youtube教程,并搜索了关于堆栈溢出的其他问题,但是身份验证仍然不起作用。我收到了一个错误400: redirect_uri_mismatch。尽管我已经检查了很多次以确认它们是一样的。
从所有的教程中,我了解到这个错误有两个主要原因:
这两个错误都有各自的个性化信息,说明这是什么类型的错配。
然而,我的公司说:你不能登录这个应用程序,因为它不符合谷歌的OAuth 2.0政策。\n\n如果您是应用程序开发人员,请在Google控制台中注册重定向URI。
这是错误的照片
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())
[1]: https://i.stack.imgur.com/2HXGP.png
发布于 2021-09-03 01:52:30
嘿,我在处理ASP.Net MVC中的这个问题,我认为原因在php中是一样的,但是无论如何,请确保在OAuth云控制台中将ur中的url复制到OAuth 2.0客户端ID中的授权重定向URI。
https://stackoverflow.com/questions/68764885
复制相似问题