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

2

9

I am using 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 with the api call, but is there any way to validate the token inside a view and get the user of that token, similar to request.user?

I need it to validate inside the consumer when using 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
Overcome answered 15/9, 2017 at 2:54 Comment(3)
Do you have permission added to you View? I am assuming your view is created using one the view classes of DRFWaitabit
@Waitabit Yes. Actually I need it in the consumers when using django channels. I have updated the question.Overcome
I have not used django-rest-frameork-jwt library but going through their doc it looks like if you have setup the library correctly, they should set the request.user in case of rest_framework_jwt.authentication.JSONWebTokenAuthenticationWaitabit
O
21

I was about to validate the token and get the user by importing VerifyJSONWebTokenSerializer class.

from rest_framework_jwt.serializers import VerifyJSONWebTokenSerializer

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

Hope this helps any body like me.

Overcome answered 16/9, 2017 at 18:45 Comment(1)
I am able to authorize my user but still django rest framework is saying unauthorized userGlinys
G
6

Use TokenBackend instead of 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)
Godderd answered 26/10, 2020 at 10:25 Comment(2)
Using this code I always get TokenBackendError: Token is invalid or expired, even for a valid fresh token. This happens indistinctively when creating the backend by hand or getting it from AccessToken.get_token_backend(). Seems related to how jwt handles payload. Anyway, having the object AccessToken created you can get information with AccessToken.payload member.Addition
What does the verify=False do?Trillby

© 2022 - 2024 — McMap. All rights reserved.