Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Xác thực Google (Google OAuth) trong Django


Sử dụng django-allauth để thêm đăng nhập Google vào trang web Django.

Các bước

  1. Tạo project trên Google Cloud Console, lấy Client ID & Secret, cấu hình redirect URI: https://127.0.0.1:8000/accounts/google/login/callback/

  2. pip install django-allauth

  3. Settings.py: thêm 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', set SITE_ID=1, AUTHENTICATION_BACKENDS.

  4. URLs: path('accounts/', include('allauth.urls'))

  5. Admin: Sites → thêm site; Social Applications → thêm Google, điền Client ID/Secret, chọn site.

  6. Template: {% load socialaccount %}<a href="{% provider_login_url 'google' %}">Login with Google</a>

Kết quả

Nút "Login with Google" → chuyển trang OAuth Google → quay lại đã đăng nhập.