微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用social_django在Goolge Oauth之后检索Django Rest Framework令牌?

如何解决如何使用social_django在Goolge Oauth之后检索Django Rest Framework令牌?

我在做什么:

我正在尝试使用Google登录按钮,以便我可以获取tokenId并将其发送到django rest api,在其中它可以使用Google Api进行验证,并从检索到的电子邮件中创建新用户(如果未注册用户) (通过电子邮件ID)),并使用认令牌(Django Rest Frameworks)响应Android客户端,以便可以将其进一步用于DRF的某些CRUD操作

我怎么样:

  1. 我创建了两个凭证,一个凭证用于Android应用程序,另一个凭证用于网络应用程序

  2. 通过从Android Studio的gradle signingReport中复制SHA-1指纹在Android凭据中添加了密码(不向凭据提供SHA-1不会获得所需的idToken)

  3. 然后我手动获取tokenId

     private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
         try {
             GoogleSignInAccount account = completedTask.getResult(ApiException.class);
    
             // Signed in successfully,show authenticated UI.
             updateUI(account);
         } catch (ApiException e) {
             // The ApiException status code indicates the detailed failure reason.
             // Please refer to the GoogleSignInStatusCodes class reference for more information.
             Log.w(this.getLocalClassName(),"signInResult:Failed code=" + e.getStatusCode());
             updateUI(null);
         }
     }
    
    
     private void  updateUI(GoogleSignInAccount account){
         Toast.makeText(this,"SUCCESS",Toast.LENGTH_SHORT).show();
         Log.w(this.getLocalClassName(),"updateUI:::SUCCESS" + " \nID TOKEN : "+account.getIdToken()+" \nEMAIL : "+account.getEmail()+" \nNAME : "+account.getdisplayName());
    
    
     } 
    
  4. 然后我点击了此链接,在Django中创建了一个API,可以在其中发布我的idToken,并通过google进行验证,如果该用户存在,则使用经过身份验证的DRF令牌进行响应(如果该用户不存在)然后创建一个新的并使用auth DRF令牌响应)

    Toptal link to create a DRF backend to exchange google Token for a DRF Token

  1. 我的Django代码如下:

urls.py

    re_path(r'^authenticate/(?P<backend>[^/]+)/$',views.exchange_token,name='url_authenticate'),

settings.py

print(SECRET_KEY)

DEBUG = env('DEBUG')

ALLOWED_HOSTS = []



INSTALLED_APPS = [
    'django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','api','rest_framework','rest_framework.authtoken','social_django',]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware','social_django.middleware.socialAuthExceptionMiddleware',]

ROOT_URLconf = 'bitconnect_proj.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates','Dirs': [],'APP_Dirs': True,'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug','django.template.context_processors.request','django.contrib.auth.context_processors.auth','django.contrib.messages.context_processors.messages','social_django.context_processors.backends','social_django.context_processors.login_redirect',],},]

TEMPLATE_CONTEXT_PROCESSORS = (
  
    'social_django.context_processors.backends',)

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',),'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',}   


AUTHENTICATION_BACKENDS = (

   'social_core.backends.google.GoogleOAuth2','django.contrib.auth.backends.ModelBackend',)

SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = env('SOCIAL_AUTH_GOOGLE_OAUTH2_KEY')
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = env('SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET')








SOCIAL_AUTH_GOOGLE_OAUTH2_ScopE = [
    'https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile',]

SOCIAL_AUTH_ADMIN_USER_SEARCH_FIELDS = ['username','first_name','email']

SOCIAL_AUTH_USERNAME_IS_FULL_EMAIL = True





SOCIAL_AUTH_PIPELINE = (    


  'social_core.pipeline.social_auth.social_details','social_core.pipeline.social_auth.social_uid','social_core.pipeline.social_auth.auth_allowed','social_core.pipeline.social_auth.social_user','social_core.pipeline.user.get_username','social_core.pipeline.social_auth.associate_by_email','social_core.pipeline.user.create_user','social_core.pipeline.social_auth.associate_user','social_core.pipeline.social_auth.load_extra_data','social_core.pipeline.user.user_details',)



Wsgi_APPLICATION = 'bitconnect_proj.wsgi.application'



DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3','NAME': BASE_DIR / 'db.sqlite3',}
}



AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',{
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',{
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',{
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',]

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True



STATIC_URL = '/static/'
 

views.py

from django.shortcuts import render
from rest_framework.decorators import api_view,permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from social_django.utils import psa
from rest_framework import serializers,status
 



# Create your views here.

class AuthSerializer(serializers.Serializer):

    access_token = serializers.CharField(allow_blank=False,trim_whitespace=True,)


@api_view(http_method_names=['POST'])
@permission_classes([AllowAny])
@psa()
def exchange_token(request,backend):

    backend = request.strategy

    print("BACKEND:::",backend)


    serializer = AuthSerializer(data=request.data)



    

    if serializer.is_valid(raise_exception=True):
        print("HERE........0")
        # This is the key line of code: with the @psa() decorator above,# it engages the PSA machinery to perform whatever social authentication
        # steps are configured in your SOCIAL_AUTH_PIPELINE. At the end,it either
        # hands you a populated User model of whatever type you've configured in
        # your project,or None.
        user = request.backend.do_auth(serializer.validated_data['access_token'])


        print("HERE......")

        if user:
            # if using some other token backend than DRF's built-in TokenAuthentication,# you'll need to customize this to get an appropriate token object
            token,_ = Token.objects.get_or_create(user=user)
            return Response({'token': token.key})

        else:
            print("HERE .............NO USER EXISTS")
            return Response(
                {'errors': {'token': 'Invalid token'}},status=status.HTTP_400_BAD_REQUEST,)


 
  1. 当我在上述端点上发出发帖请求时,我得到了:

“ / home / thebitshoes / Desktop / Environments / voiceconnect_new / lib / python3.8 / site-packages / social_core / utils.py”, 包装中的第256行 提高AuthForbidden(args [0])

异常类型:AuthForbidden位于/ authenticate / google-oauth2 / 例外值:不允许您的凭据

请帮助我,谢谢!!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。