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
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With