url.py
urlpatterns = [
path('admin/', admin.site.urls),
path('auth/', include('rest_auth.urls')),
path('', GoogleLogin.as_view()),
path('auth/google/callback/', google_callback, name='google_callback'),
path('auth/google/url/', google_views.oauth2_login)
]
views.py
import urllib.parse
from allauth.socialaccount.providers.google import views as google_views
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
from django.contrib import admin
from django.shortcuts import redirect
from django.urls import include, path, reverse
from rest_auth.registration.views import SocialLoginView
class GoogleLogin(SocialLoginView):
adapter_class = google_views.GoogleOAuth2Adapter
client_class = OAuth2Client
@property
def callback_url(self):
return self.request.build_absolute_uri(reverse('google_callback'))
def google_callback(request):
params = urllib.parse.urlencode(request.GET)
return redirect(f' http://127.0.0.1:8000/auth/google/callback/')
Web 应用程序的客户端 ID
URI :http://127.0.0.1:8000 授权重定向 URI:http://127.0.0.1:8000/auth/google/callback/
错误: 授权错误 错误 400:redirect_uri_mismatch
您无法登录此应用,因为它不符合 Google 的 OAuth 2.0 政策。
如果您是应用开发者,请在 Google Cloud Console 中注册重定向 URI。 了解更多 本节内容由应用程序开发者提供。此内容尚未经过 Google 审核或验证。 如果您是应用开发者,请确保这些请求详细信息符合 Google 政策。
redirect_uri: http://localhost:8000/auth/google/callback/
请帮助我。先感谢您。 django-rest-auth 使用谷歌身份验证任何参考文档请分享我。
我有问题
User
模型带有 UUID 主键,恢复默认 id
字段后它开始工作
https://github.com/iMerica/dj-rest-auth/issues/551#issuecomment-1858911936
我使用 django-allauth 和 dj-rest-auth 的示例
用户/views.py
class GoogleLoginRedirect(RedirectView):
url = "https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=<REDIRECT_URL(WITH OUT SLASH IN THE END)>&prompt=consent&response_type=code&client_id=<CLIENT_ID>&scope=openid%20email%20profile&access_type=offline"
permanent = True
def get_redirect_url(self, *args, **kwargs):
return self.url
import requests
class GoogleCallback(View):
def get(self, request, *args, **kwargs):
code = request.GET["code"]
response = requests.post("http://localhost:8000/dj-rest-auth/google/", json={
"code": code
})
django_response = HttpResponse(
content=response.content,
status=response.status_code,
)
for k, v in response.headers.items():
django_response[k] = v
return django_response
url.py
path('dj-rest-auth/google/', GoogleLogin.as_view(), name='google_login'),
path("dj-rest-auth/google/login/", view=GoogleLoginRedirect.as_view(), name="google_redirect"),
path("dj-rest-auth/google/callback/", view=GoogleCallback.as_view(), name="google_callback"),
UUID 主键不适用于 django-allauth = "~0.56.1" dj-rest-auth =“~5.0.2”