How to get username from Django Rest Framework JWT token

北城余情 提交于 2019-12-04 05:10:48

Basically you could do this

username = request.user.username

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/

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