เว็บนักพัฒนาหลายแห่งมี Google Social Authentication ซึ่งสะดวก บทความนี้สอนสร้างโปรเจกต์ Django Google Login
ขั้นตอนเตรียม Google Console
- ไปที่ https://console.cloud.google.com/apis/dashboard สร้างโปรเจกต์
- ไป OAuth consent screen สร้างหน้าจอ และ save & continue
- ไป Credentials คลิก "Create credentials" → "OAuth client ID"
- เลือก Web application เพิ่ม URL 2 รายการ:
- https://127.0.0.1:8000/
- https://127.0.0.1:8000/accounts/github/login/callback/
- ได้ Client ID และ Secret Key เก็บไว้
ตัวอย่างการตั้งค่า 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" # ชื่อแอป
]
SOCIALACCOUNT_PROVIDERS = {
'google': {
'SCOPE': ['profile', 'email'],
'AUTH_PARAMS': {'access_type': 'online'}
}
}
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend",
"allauth.account.auth_backends.AuthenticationBackend",
)
ใน 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("googleauthentication.urls"))
]
ใน urls.py ของแอป:
from django.urls import path
from . import views
urlpatterns = [
path('', views.home),
]
ใน views.py:
from django.shortcuts import render
def home(request):
return render(request, 'home.html')
สร้าง templates/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>
รันคำสั่ง:
python manage.py makemigrations python manage.py migrate python manage.py createsuperuser
เข้า Admin Panel → Sites เพิ่ม site url: https://127.0.0.1:8000
→ Social Applications เพิ่ม application เลือก provider google ใส่ Client ID และ Secret
เอาต์พุต
