谷歌登录姜戈睡觉框架+allauth+睡觉-auth [英] Google login in django rest framework + allauth + rest-auth

本文介绍了谷歌登录姜戈睡觉框架+allauth+睡觉-auth的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用allauth睡觉-auth在Django中实现谷歌身份验证。经过多个小时的研究,我发现的解决方案在我的项目中都不起作用。

我的代码基于GitHub问题:https://github.com/Tivix/django-rest-auth/issues/403

和一篇文章: https://medium.com/@gonzafirewall/google-oauth2-and-django-rest-auth-92b0d8f70575

我还使用Google客户端ID客户端密码创建了Social Application对象

我在Google控制台中的项目设置:

JavaScript授权来源:http://localhost:8000 授权重定向URI:http://localhost:8000/api/v1/users/login/google/callback/

我的代码

Providers.py

from allauth.socialaccount.providers.google.provider import GoogleProvider


class GoogleProviderMod(GoogleProvider):
    def extract_uid(self, data):
        return str(data['sub'])

Adapters.py

from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from google.auth.transport import requests
from google.oauth2 import id_token

from myproj.users.providers import GoogleProviderMod


class GoogleOAuth2AdapterIdToken(GoogleOAuth2Adapter):
    provider_id = GoogleProviderMod.id

    def complete_login(self, request, app, token, **kwargs):
        idinfo = id_token.verify_oauth2_token(token.token, requests.Request(), app.client_id)
        if idinfo["iss"] not in ["accounts.google.com", "https://accounts.google.com"]:
            raise ValueError("Wrong issuer.")
        extra_data = idinfo
        login = self.get_provider().sociallogin_from_response(request, extra_data)
        return login

views.py

from allauth.socialaccount.providers.oauth2.client import OAuth2Client
from rest_auth.registration.serializers import SocialLoginSerializer
from rest_auth.registration.views import SocialLoginView

from myproj.users.adapters import GoogleOAuth2AdapterIdToken


class GoogleLoginView(SocialLoginView):
    adapter_class = GoogleOAuth2AdapterIdToken
    callback_url = "http://localhost:8000/api/v1/users/login/google/callback/"
    client_class = OAuth2Client
    serializer_class = SocialLoginSerializer

urls.py

from allauth.socialaccount.providers.oauth2.views import OAuth2CallbackView
from django.urls import path

from myproj.users.adapters import GoogleOAuth2AdapterIdToken
from myproj.users.views import GoogleLoginView

app_name = "users"
urlpatterns = [
    path(
        "login/google/",
        GoogleLoginView.as_view(),
        name="google_login"
    ),
    path(
        "login/google/callback/",
        OAuth2CallbackView.adapter_view(GoogleOAuth2AdapterIdToken),
        name="google_callback"
    ),
]

settings.py

AUTHENTICATION_BACKENDS = [
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend",
]
ACCOUNT_DEFAULT_HTTP_PROTOCOL = "http"

我在登录页面将ID令牌(从Google‘登录’按钮返回)作为code参数传递时,出现错误:

allauth.socialaccount.providers.oauth2.client.OAuth2Error: Error retrieving access token: b'{ "error": "invalid_grant", "error_description": "Malformed auth code." }' 响应代码为400。

实际上,即使我向代码传递一些随机文本,错误也是一样的。

谢谢您的帮助!

推荐答案

我还集成了djangorest framework+django-allauth+django-睡觉-auth+djangorest framework-jwt。 但是,我只是在Google上实现了登录,所以用户不能手动注册。

以下是我的代码:

views.py

from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
from rest_auth.registration.views import SocialLoginView


class GoogleLogin(SocialLoginView):
    adapter_class = GoogleOAuth2Adapter
    client_class = OAuth2Client

urls.py

...
path('auth/google', GoogleLogin.as_view(), name='google_login'),
...

settings.py

INSTALLED_APPS = [
    ...
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google',
    ...
]
SITE_ID = 1
REST_USE_JWT = True    # this is for djangorestframework-jwt

[更新]
要在SocialLoginView终结点上使用codeparams:

  • 创建可访问的重定向URI(我认为它在前端,也可以使用简单视图)
  • 使用https回调(我在本地开发时使用ngrok)
  • 直接访问url(不要使用Google OAuth playgroud获取代码,因为client_id不同),或者直接复制OAuth palygroud上的请求url,更改redirect_uri和cliend_id。这是链接 https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=<https_callback>&prompt=consent&response_type=code&client_id=<cliend_id>&scope=email&access_type=offline

这篇关于谷歌登录姜戈睡觉框架+allauth+睡觉-auth的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆