如何从Django Rest Framework JWT令牌获取用户名

时间:2021-07-13 19:35:14

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 *. 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.

我正在使用Django Rest Framework,我已经包含了一个名为REST framework JWT Auth的第三方软件包。当您向某个路由发送用户名/密码时,它会返回一个令牌。然后需要令牌才能获得某些路由的许可。但是,如何从令牌中获取用户名?我查看了整个软件包文档并浏览了*。它是一个JSON Web令牌,我假设有一个像username = decode_token(token)的方法,但我还没有找到这样的方法。

2 个解决方案

#1


4  

Basically you could do this

基本上你可以做到这一点

username = request.user.username

#2


1  

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

对我来说,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/

您可以在此处阅读分步指南:http://blog.sadafnoor.me/blog/a-django-rest-framework-jwt-middleware-to-support-request-user/

#1


4  

Basically you could do this

基本上你可以做到这一点

username = request.user.username

#2


1  

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

对我来说,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/

您可以在此处阅读分步指南:http://blog.sadafnoor.me/blog/a-django-rest-framework-jwt-middleware-to-support-request-user/