You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于编写JavaScript虚拟环境目录关联函数及DRF Social OAuth2注册返回令牌的技术咨询

2. Return Token on Email/Password Registration with DRF Social OAuth2

Got it, DRF Social OAuth2 is built for social authentication flows, so it doesn't handle token returns for standard email/password registration by default. But we can easily customize the registration view to generate and return an OAuth2 token right after the user is created. Here's how to do it:

Step 1: Create a Custom Registration Serializer

First, make sure you have a serializer that properly creates users from email, username, and password:

from rest_framework import serializers
from django.contrib.auth.models import User

class RegisterSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True, required=True)

    class Meta:
        model = User
        fields = ('email', 'username', 'password')

    def create(self, validated_data):
        # Create user and set hashed password
        user = User.objects.create(
            username=validated_data['username'],
            email=validated_data['email']
        )
        user.set_password(validated_data['password'])
        user.save()
        return user

Step 2: Customize the Registration View to Generate Token

We'll extend DRF's CreateAPIView and use DRF Social OAuth2's token generation logic to return a token after user creation. Note: You'll need to have an OAuth2 Application created in your Django Admin first (under "OAuth2 Provider" → "Applications").

from rest_framework import generics, status
from rest_framework.response import Response
from django.contrib.auth.models import User
from oauth2_provider.models import Application
from oauth2_provider.views.mixins import OAuthLibMixin
from drf_social_oauth2.views import TokenView
from .serializers import RegisterSerializer

class RegisterWithTokenView(generics.CreateAPIView, OAuthLibMixin):
    queryset = User.objects.all()
    serializer_class = RegisterSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()

        try:
            # Get your OAuth2 application (replace 'Your App Name' with your actual app name)
            app = Application.objects.get(name='Your App Name')
        except Application.DoesNotExist:
            return Response(
                {'error': 'OAuth2 application not found'},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

        # Construct a password grant request to generate token
        token_request = request._request
        token_request.POST = {
            'grant_type': 'password',
            'username': user.username,
            'password': request.data['password'],
            'client_id': app.client_id,
            'client_secret': app.client_secret,
        }

        # Use DRF Social OAuth2's TokenView to generate the token response
        token_view = TokenView.as_view()
        token_response = token_view(token_request)

        return Response(token_response.data, status=status.HTTP_201_CREATED)

Step 3: Add the View to Your URLs

Update your urls.py to include the new registration endpoint:

from django.urls import path
from .views import RegisterWithTokenView

urlpatterns = [
    path('api/register/', RegisterWithTokenView.as_view(), name='register-with-token'),
    # Your other URLs here...
]

Quick Notes

  • Make sure your OAuth2 Application in Django Admin has the correct redirect URIs (you can set it to http://localhost:8000 for development).
  • If you're using a custom user model, adjust the serializer and view to use your model instead of Django's default User.
  • Add error handling for edge cases (like duplicate usernames/emails) if needed—you can catch exceptions in the create method and return appropriate responses.

内容的提问来源于stack exchange,提问作者Rocky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 21:52:42