在视图或消费者中使用 jwt 令牌验证并获取用户

Validate and get the user using the jwt token inside a view or consumer

我在 api 调用中使用 django-rest-framework for the REST API. Also, for JSON web token authentication I am using django-rest-framework-jwt. After a successful login, the user is provided with a token. I have found how to verify a token,但是有什么方法可以在视图中验证令牌并获取该令牌的用户,类似于 request.user?

我需要它在使用时在消费者内部进行验证 django-channels:

def ws_connect(message):
    params = parse_qs(message.content["query_string"])
    if b"token" in params:
        token = params[b"token"][0]

    # validate the token and get the user object

    # create an object with that user

我正要验证令牌并通过导入 VerifyJSONWebTokenSerializer 获取用户 class。

from rest_framework_jwt.serializers import VerifyJSONWebTokenSerializer

data = {'token': token}
valid_data = VerifyJSONWebTokenSerializer().validate(data)
user = valid_data['user']

希望这对像我这样的人有帮助。

使用TokenBackend代替VerifyJSONWebTokenSerializer

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)