Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 325
Robin Avatar asked Sep 15 '17 02:09

Robin


People also ask

How do I verify my token with JWT?

Verify RS256-signed tokens Go to Dashboard > Applications. Go to the Settings view, and open Advanced Settings. Go to the Certificates view, locate the Signed Certificate field, and copy the Public Key. Navigate to the JWT.io website, locate the Algorithm dropdown, and select RS256.

How do I authenticate a user with JWT?

To authenticate a user, a client application must send a JSON Web Token (JWT) in the authorization header of the HTTP request to your backend API. API Gateway validates the token on behalf of your API, so you don't have to add any code in your API to process the authentication.


2 Answers

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.

like image 50
Robin Avatar answered Nov 04 '22 11:11

Robin


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)
like image 20
Arpan Kushwaha Avatar answered Nov 04 '22 11:11

Arpan Kushwaha