return token after registration with django-rest-framework-simplejwt

后端 未结 3 1905
独厮守ぢ
独厮守ぢ 2021-02-04 22:46

I\'m using django-rest-framework-simplejwt and was wondering if it\'s possible to return a token after registering a user?

This post has a solution for another jwt packa

相关标签:
3条回答
  • 2021-02-04 23:11

    another possible solution is:

    in your view

    from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
    from rest_framework_simplejwt.tokens import AccessToken, RefreshToken
    
    
    @login_required
    def index(request):
        tokenr = TokenObtainPairSerializer().get_token(request.user)  
        tokena = AccessToken().for_user(request.user)
        return render(request,'myview/index.html', {"refresh" : str(tokenr),"access" : str(tokena)} )
    

    I used @login_required just to be sure we have a request.user authenticated, but you could pass a dict instead

    0 讨论(0)
  • 2021-02-04 23:23

    I just solved my own question. Let me know if you have any comments. Thanks!

    serializers.py

    class RegisterUserSerializer(serializers.ModelSerializer):
        """Serializer for creating user objects."""
    
        tokens = serializers.SerializerMethodField()
    
        class Meta:
            model = models.User
            fields = ('id', 'password', 'email', 'tokens')
            extra_kwargs = {'password': {'write_only': True}}
    
        def get_tokens(self, user):
            tokens = RefreshToken.for_user(user)
            refresh = text_type(tokens)
            access = text_type(tokens.access_token)
            data = {
                "refresh": refresh,
                "access": access
            }
            return data
    
        def create(self, validated_data):
            user = models.User(
                email=validated_data['email']
            )
            user.set_password(validated_data['password'])
            user.save()    
            return user
    

    views.py

    class UserListView(generics.ListCreateAPIView):
        """Handles creating and listing Users."""
        queryset = User.objects.all()
    
    def create(self, request, *args, **kwargs):
            serializer = RegisterUserSerializer(data=request.data)
            if serializer.is_valid():
                self.perform_create(serializer)
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
    0 讨论(0)
  • 2021-02-04 23:24

    I guess, you can do something like this :

    def custom_registration_view(request):
        //code to validate & register your user
        payload = jwt_payload_handler(user)
        return HttpResponse(jwt_encode_handler(payload), 201)
    

    The payload_handler, encode_handler and decode_handler you can specify in settings file.

    0 讨论(0)
提交回复
热议问题