How to get username from Django Rest Framework JWT token

后端 未结 3 1038
猫巷女王i
猫巷女王i 2021-02-13 16:38

I am using Django Rest Framework and i\'ve included a 3rd party package called REST framework JWT Auth. It returns a token when you send a username/password to a certain route.

相关标签:
3条回答
  • 2021-02-13 17:05

    For me with Django (2.0.1), djangorestframework (3.7.7), djangorestframework-jwt (1.11.0).

    I had to do following to get my use back user from token:

            token = request.META.get('HTTP_AUTHORIZATION', " ").split(' ')[1]
            print(token)
            data = {'token': token}
            try:
                valid_data = VerifyJSONWebTokenSerializer().validate(data)
                user = valid_data['user']
                request.user = user
            except ValidationError as v:
                print("validation error", v)
    

    Or you can write a middleware that would set user based on their token.

    0 讨论(0)
  • 2021-02-13 17:08

    Basically you could do this

    username = request.user.username
    
    0 讨论(0)
  • 2021-02-13 17:25

    For me, this worked as RestFrameworkJWT is no longer maintained. So I used the rest_framework_simplejw package.

    from rest_framework_simplejwt.backends import TokenBackend
    token = request.META.get('HTTP_AUTHORIZATION', " ").split(' ')[1]
            data = {'token': token}
            try:
                valid_data = TokenBackend(algorithm='HS256').decode(token,verify=False)
                user = valid_data['user']
                request.user = user
            except ValidationError as v:
                print("validation error", v)
    
    0 讨论(0)
提交回复
热议问题