Implementing OAuth2 Authentication in Django REST Framework with python-social-auth

Weibo Open Platform Setup

Register your application on the Weibo Open Platform to obtain API credentials. After completing developer verification, create a new application to receive your unique App Key and App Secret.

OAuth2.0 Configuration

During development, enable test mode to bypass official review:

  1. Add test user accounts authorized to authenticate through your application
  2. Configure advanced permissions to access user profile information

Manual OAuth2 Flow Implementation

Understanding the underlying OAuth2 flow helps troubleshoot integration issues. Here's a direct implementation:

# OAuth2 configuration constants
WEIBO_APP_KEY = "your_application_key"
WEIBO_APP_SECRET = "your_application_secret"
CALLBACK_URL = "http://localhost:8000/auth/callback/weibo"

def construct_authorization_endpoint():
    """Generates the authorization URL for user consent"""
    base_endpoint = "https://api.weibo.com/oauth2/authorize"
    query_string = f"client_id={WEIBO_APP_KEY}&redirect_uri={CALLBACK_URL}&response_type=code"
    return f"{base_endpoint}?{query_string}"

def exchange_code_for_credentials(auth_code):
    """Trades authorization code for access credentials"""
    token_endpoint = "https://api.weibo.com/oauth2/access_token"
    
    token_request = {
        "client_id": WEIBO_APP_KEY,
        "client_secret": WEIBO_APP_SECRET,
        "grant_type": "authorization_code",
        "code": auth_code,
        "redirect_uri": CALLBACK_URL
    }
    
    import requests
    token_result = requests.post(token_endpoint, data=token_request)
    return token_result.json()
    # Sample response: {"access_token":"...","expires_in":157679999,"uid":"..."}

def retrieve_user_profile(access_data):
    """Fetches user profile using obtained credentials"""
    profile_endpoint = "https://api.weibo.com/2/users/show.json"
    request_params = f"access_token={access_data['access_token']}&uid={access_data['uid']}"
    
    import requests
    user_profile = requests.get(f"{profile_endpoint}?{request_params}")
    return user_profile.json()

python-social-auth Integration

The python-social-auth ecosystem streamlines OAuth2 provider integration. Follow these steps:

Package Installation

pip install social-auth-app-django

Django Application Configuration

Add the social authentication module to your installed applications:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    ...
    'social_django',
]

Database Schema Migration

Execute migrations to create the necessary database tables:

python manage.py migrate

This creates five tables for storing social authentication relationships and tokens.

Authentication Backends Configuration

Define multiple authentication methods in your project settings:

AUTHENTICATION_BACKENDS = (
    'users.backends.EmailOrPhoneBackend',
    'social_core.backends.weibo.WeiboOAuth2',
    'social_core.backends.qq.QQOAuth2',
    'social_core.backends.weixin.WeixinOAuth2',
    'django.contrib.auth.backends.ModelBackend',
)

URL Routing Setup

Include social authentication endpoints in your URL configuration:

from django.urls import path, include

urlpatterns = [
    path('api/auth/', include('social_django.urls', namespace='social')),
    ...
]

Ensure existing login endpoints terminate with $ to prevent route conflicts.

Template Context Processors

Add social authentication data to template context:

TEMPLATES = [{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            ...
            'social_django.context_processors.backends',
            'social_django.context_processors.login_redirect',
        ],
    },
}]

Provider Callback Configuration

Set the redirect URI in your Weibo application dashboard:

http://localhost:8000/api/auth/callback/weibo/

Update to your production domain before deployment.

API Credentials Management

Store provider secrets securely in environment-specific settings:

# Third-party authentication credentials
SOCIAL_AUTH_WEIBO_KEY = os.environ.get('WEIBO_APP_KEY')
SOCIAL_AUTH_WEIBO_SECRET = os.environ.get('WEIBO_APP_SECRET')

SOCIAL_AUTH_QQ_KEY = os.environ.get('QQ_APP_ID')
SOCIAL_AUTH_QQ_SECRET = os.environ.get('QQ_APP_KEY')

SOCIAL_AUTH_WEIXIN_KEY = os.environ.get('WECHAT_APP_ID')
SOCIAL_AUTH_WEIXIN_SECRET = os.environ.get('WECHAT_APP_SECRET')

Post-Authentication Redirect

Configure the destination after succesfull social authentication:

SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/dashboard/'

Custom Authentication Response for JWT Frontends

For JavaScript frontends using JWT authentication, overrdie the default redirect behavior:

Copy the social_core package to your project (e.g., lib/social_core) and modify actions.py:

Original implementation:

return backend.strategy.redirect(url)

Customized version with JWT support:

# Custom social authentication completion for JWT-based applications
from rest_framework_jwt.utils import jwt_payload_handler, jwt_encode_handler

def social_auth_complete(backend, user, redirect_url, **kwargs):
    """Completes social auth and sets JWT cookies for frontend"""
    response = backend.strategy.redirect(redirect_url)
    
    # Generate JWT token for authenticated user
    payload = jwt_payload_handler(user)
    jwt_token = jwt_encode_handler(payload)
    
    # Set secure cookies for frontend authentication
    display_name = user.get_full_name() if user.get_full_name() else user.username
    response.set_cookie("username", display_name, max_age=86400, httponly=False)
    response.set_cookie("auth_token", jwt_token, max_age=86400, httponly=True)
    
    return response

Automatic User Account Binding

The social authentication system handles user account relationships automatically:

  • Authenticated users linking a social account will have it associated with their current profile
  • New users authenticating via social login receive a created account with automatic provider binding
  • Returning social authentication attempts recognize and login to the previously linked account

Tags: django-rest-framework python-social-auth OAuth2 weibo-api jwt-authentication

Posted on Mon, 06 Jul 2026 16:24:31 +0000 by Eclipse