问题描述
我在做什么:
我正在尝试使用Google登录按钮,以便我可以获取tokenId并将其发送到django rest api,在其中它可以使用Google Api进行验证,并从检索到的电子邮件中创建新用户(如果未注册用户) (通过电子邮件ID)),并使用默认令牌(Django Rest Frameworks)响应Android客户端,以便可以将其进一步用于DRF的某些CRUD操作
我怎么样:
-
通过从Android Studio的gradle signingReport中复制SHA-1指纹在Android凭据中添加了密码(不向凭据提供SHA-1不会获得所需的idToken)
-
然后我手动获取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()); }
-
然后我点击了此链接,在Django中创建了一个API,可以在其中发布我的idToken,并通过google进行验证,如果该用户存在,则使用经过身份验证的DRF令牌进行响应(如果该用户不存在)然后创建一个新的并使用auth DRF令牌响应)
Toptal link to create a DRF backend to exchange google Token for a DRF Token
- 我的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,)
- 当我在上述端点上发出发帖请求时,我得到了:
“ / 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 (将#修改为@)