Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การเปิดใช้งาน GitHub OAuth ใน Django


เว็บนักพัฒนาหลายแห่งมี GitHub Social Authentication บทความนี้สอนเพิ่ม GitHub Auth ใน Django

ไปที่ https://github.com/settings/developers/ สร้าง OAuth Application เพิ่ม URL 2 รายการ:

  • https://127.0.0.1:8000/
  • https://127.0.0.1:8000/accounts/github/login/callback
ได้ Client ID และ Secret Key

ตัวอย่าง

ติดตั้ง 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"

ใน urls.py ของโปรเจกต์:

from django.contrib import admin
from django.urls import path, include
urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('allauth.urls')),
    path('', include("githubAuthentication.urls"))
]

เข้า https://localhost:8000/admin → Social Applications เพิ่ม application ใส่ Client ID, Secret Key, Provider: github

ใน Sites คลิก example.com เพิ่มและ save

สร้าง 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' %}?next=https://github.com">login with github</a>
</body> </html>

ใน views.py:

from django.shortcuts import render
def home(request):
    return render(request, "home.html")

ใน urls.py ของแอป:

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

เอาต์พุต

การเปิดใช้งาน GitHub OAuth ใน Django