在 Django 中启用 GitHub OAuth


在许多开发者网站上,我们都会看到 GitHub 社交认证,这非常方便。在本文中,我们将了解如何在 Django 网站中添加 Github 认证。

访问 https://github.com/settings/developers/ 并创建一个 OAuth 应用程序,并添加以下两个 URL

然后,您将获得一个客户端 ID 和一个密钥。现在,让我们进入编码部分。

示例

安装 **django-allauth** 库 -

pip install django-allauth

在 **settings.py** 中添加以下代码行 -

INSTALLED_APPS = [
   ##################
#
#
#
#

   'django.contrib.sites',
   'allauth',
   'allauth.account',
   'allauth.socialaccount',
   'allauth.socialaccount.providers.github',
   'githubAuthentication'
]

SITE_ID = 1
AUTHENTICATION_BACKENDS= [
   'django.contrib.auth.backends.ModelBackend',
   'allauth.account.auth_backends.AuthenticationBackend'
]

LOGIN_REDIRECT_URL="https://github.com"

在 INSTALLED_APPS 中,我们添加了所需的导入库,然后添加了 GitHub 默认身份验证后端。我们还启用了重定向 URL,它将指示登录后重定向到的位置。

在项目根目录的 **urls.py** 中 -

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

urlpatterns = [
   path('admin/', admin.site.urls),

   # this is module path copy this as it is
path('accounts/', include('allauth.urls')),

# this is my app path
path('', include("githubAuthentication.urls"))
]

在这里,我们添加了需要添加的默认路径;它是 allauth 库路径,用于启用 GitHub 登录。第二个是我们创建的应用程序路径。

现在访问 https://:8000/admin 并转到社交应用程序。

然后,添加一个应用程序 -

粘贴您之前复制的 **客户端 ID** 和 **密钥**,名称应为应用程序名称,选择提供程序 **github**。

在 **站点** 部分,点击 **example.com**,然后点击箭头键并点击保存。这将在您的 Django 项目中注册 **github** 作为身份验证后端。

现在,在 **templates** 文件夹中创建 **home.html** 并添加以下代码行 -

<!DOCTYPE html>
<html>
   <head>
      <title>tut</title>
    </head>
    <body>
      {% load socialaccount %}
      {% providers_media_js %}
<a href="{% provider_login_url 'github' method='js_sdk' %}?n
ext=https://github.com">login with github</a>
   </body>
</html>

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

在 **view.py** 中 -

from django.shortcuts import render

# Create your views here.
def home(request):
   return render(request,"home.html")

我们在这里渲染了我们的前端

在 **urls.py**(应用程序 url)中 -

from django.urls import path,include
from . import views
urlpatterns = [
   path('',views.home, name="Home" ),

]

我们在这里设置了 url 并渲染了我们的视图。

一切就绪,现在您可以继续检查输出。

输出


更新于: 2021-08-26

619 次浏览

开启您的 职业生涯

通过完成课程获得认证

开始
广告

© . All rights reserved.