Chuyển đến nội dung chính

Bài 11: Social Auth & OAuth2

Social authentication với django-allauth (Google, GitHub, Facebook). OAuth2 Provider với django-oauth-toolkit. SSO integration, account linking, custom social adapters.

💻 Lập trình — Bài 11 Bài 11: Social Auth & OAuth2

Django: Từ Cơ bản đến Nâng cao

Phần 3: Authentication & Security

xdev.asia

1. django-allauth Setup

pip install django-allauth
# settings.py
INSTALLED_APPS = [
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google',
    'allauth.socialaccount.providers.github',
]

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

ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
LOGIN_REDIRECT_URL = '/dashboard/'

2. Google OAuth2

# settings.py
SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'APP': {
            'client_id': os.environ['GOOGLE_CLIENT_ID'],
            'secret': os.environ['GOOGLE_CLIENT_SECRET'],
        },
        'SCOPE': ['profile', 'email'],
        'AUTH_PARAMS': {'access_type': 'online'},
    },
}

# urls.py
urlpatterns = [
    path('accounts/', include('allauth.urls')),
]

3. Custom Social Adapter

from allauth.socialaccount.adapter import DefaultSocialAccountAdapter

class CustomSocialAdapter(DefaultSocialAccountAdapter):
    def pre_social_login(self, request, sociallogin):
        # Tự động link account nếu email đã tồn tại
        email = sociallogin.account.extra_data.get('email')
        if email:
            try:
                user = User.objects.get(email=email)
                sociallogin.connect(request, user)
            except User.DoesNotExist:
                pass

    def populate_user(self, request, sociallogin, data):
        user = super().populate_user(request, sociallogin, data)
        user.role = 'customer'
        return user

# settings.py
SOCIALACCOUNT_ADAPTER = 'accounts.adapters.CustomSocialAdapter'

4. OAuth2 Provider

pip install django-oauth-toolkit
# settings.py
INSTALLED_APPS = [..., 'oauth2_provider']

OAUTH2_PROVIDER = {
    'SCOPES': {
        'read': 'Read scope',
        'write': 'Write scope',
    },
    'ACCESS_TOKEN_EXPIRE_SECONDS': 3600,
}

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
    ],
}

# urls.py
urlpatterns = [
    path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')),
]

5. Social Auth trong DRF

from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from dj_rest_auth.registration.views import SocialLoginView

class GoogleLogin(SocialLoginView):
    adapter_class = GoogleOAuth2Adapter

# urls.py
urlpatterns = [
    path('api/auth/google/', GoogleLogin.as_view()),
]

Bài tiếp theo: Security Best Practices.