How to get username from Django Rest Framework JWT token

会有一股神秘感。 提交于 2019-12-05 21:42:23

问题


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. Then the token is needed for permission to certain routes. However, how do I get the username from the token? I've looked all through the package documentation and went through StackOverflow. It is a JSON Web Token and I am assuming there is a method like username = decode_token(token) but I haven't found such a method.


回答1:


Basically you could do this

username = request.user.username



回答2:


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.

You can read step by step guide here: http://blog.sadafnoor.me/blog/a-django-rest-framework-jwt-middleware-to-support-request-user/



来源:https://stackoverflow.com/questions/39823363/how-to-get-username-from-django-rest-framework-jwt-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!