首页 > 解决方案 > DRF & React:如何通过单击“使用 google 登录”将社交应用程序令牌添加到数据库

问题描述

我不知道我在做什么。我正在尝试从 React 应用程序使用 Google 登录。所以我在谷歌云平台上创建了一个项目,设置Authorized JavaScript origins url :http://localhost:3000Authorized redirect URIs http://127.0.0.1:8000/accounts/google/login/callback/并获得Clint IdSecret key。然后,我使用这些 ID 和密钥从 Django 管理站点创建了一个社交应用程序。

然后我写这段代码:

设置.py:

INSTALLED_APPS = [
    'myapp',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'rest_framework',
    'corsheaders',
    'rest_framework.authtoken',
    'rest_auth',
    'rest_auth.registration',
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google', #google
]

SITE_ID = 1

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
   'rest_framework.permissions.IsAuthenticated',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ],
    'DEFAULT_FILTER_BACKENDS':['django_filters.rest_framework.DjangoFilterBackend'],
}

网址.py:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls')),
    path('api/rest-auth/', include('rest_auth.urls')),
    path('api/rest-auth/registration/', include('rest_auth.registration.urls')),
    
    path('accounts/', include('allauth.urls')),

在 Reactjs 中:

//...code
    responseGoogle = (response) => {
        console.log(response);
      }
//..code
<GoogleLogin
    clientId="634453711672-3lf3sk6g4dl74q428n14jc4n6n592d99.apps.googleusercontent.com"
    buttonText="Login"
    onSuccess={this.responseGoogle}
    onFailure={this.responseGoogle}
    cookiePolicy={'single_host_origin'}
  />

当我单击此登录按钮,然后选择我的 gmail 帐户时,它会控制台记录一个对象。 kx{Os: mx {$R: "**************", Ne: "Asif Biswas", ET: "Asif", GR: "Biswas",....}...}. 但不会在数据库中创建任何社交帐户

我的目标是:单击登录按钮 > 验证用户(在本地存储中设置令牌)> 创建社交帐户和应用程序令牌(在数据库中)。

有什么建议吗?

标签: reactjsdjangodjango-rest-frameworkgoogle-oauth

解决方案


推荐阅读