Django 中的 Google 身份验证

pythonserver side programmingprogramming更新于 2025/10/1 2:52:17

在许多开发者网站中,我们可以看到非常方便的 Google 社交身份验证。在本文中,我们将了解如何创建 Django Google 登录项目。

  • 然后,选择 Web 应用程序,并添加这两个 URL −

现在,您将获得一个客户端 ID 和一个密钥,请将它们安全地保存在您的文件中。

示例

创建一个 Django 项目和一个应用程序。

在 settings.py 中 −

SITE_ID = 1
LOGIN_REDIRECT_URL = "/"

INSTALLED_APPS = [
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   "django.contrib.sites", # <--
   "allauth", # <--
   "allauth.account", # <--
   "allauth.socialaccount", # <--
   "allauth.socialaccount.providers.google",
   "googleauthentication" #this is my app name ,you can name your app anything you want
]
SOCIALACCOUNT_PROVIDERS = {
   'google': {
      'SCOPE': [
         'profile',
         'email',
      ],
      'AUTH_PARAMS': {
         'access_type': 'online',
      }
   }
}

#add this in the end of file
AUTHENTICATION_BACKENDS = (
   "django.contrib.auth.backends.ModelBackend",
   "allauth.account.auth_backends.AuthenticationBackend",
)

在这里,我们定义了一个重定向 URL。在已安装的应用程序中,我们定义了用于身份验证的重要后端。然后,我们定义了社交帐户提供程序,它将告诉我们应该使用什么进行登录(这里我们使用 Google)。我们还定义了它应该存储用户的哪些数据。

现在,在项目的 urls.py 中,添加以下 −

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
   path('admin/', admin.site.urls),
   path("accounts/", include("allauth.urls")), #most important
   path('',include("googleauthentication.urls")) #my app urls
]

这里我们添加了需要添加的默认路径,即用于启用 Google 登录的 allauth 库路径。第二个是我们创建的 app 路径。

在 app 的 urls.py 中 −

from django.urls import path
from . import views
urlpatterns = [
   path('',views.home),
]

在这里,我们设置了 urls 并在 home url 上呈现了我们的视图。

在 view.py 中 −

from django.shortcuts import render

# 在此处创建您的视图。
def home(request):
   return render(request,'home.html')

我们只是在此处呈现了前端。

在应用程序的主目录中创建一个 template 文件夹,并添加一个文件 home.html,内容如下 −

<!DOCTYPE html>
<html>
   <head>
      <title>Google Registration</title>
   </head>
   <body>
      {% load socialaccount %}
      <h1>My Google Login Project</h1>
      <a href="{% provider_login_url 'google'%}?next=/">Login with Google</a>
   </body>
</html>

在这里,我们渲染了 JS 并在前端加载了 allauth 库。在 <a> 中,我们提供了 Google 登录页面,并在该页面上设置了默认的 Google 登录页面。

现在,在终端 − 上运行以下命令

python manage.py makemigrations
python manage.py move

接下来,创建一个 超级用户。

python manage.py createsuperuser

然后,启动服务器并转到管理面板。转到站点并添加一个具有网址名称和显示名称的站点:http://127.0.0.1:8000

转到社交应用程序并添加应用程序。选择您之前添加的站点 −

这会将 Google 注册为您的 Django 项目上的身份验证后端。一切已设置,现在您可以继续检查输出。

输出


相关文章


有用资源