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 StackOverflow. 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.
-
You have user object in request. Or you are not doing this in view?Sardorbek Imomaliev– Sardorbek Imomaliev2016-10-03 04:24:50 +00:00Commented Oct 3, 2016 at 4:24
-
I am doing this in view but I am new to Django so I don't fully understand how it works. Can you elaborate?Gary Holiday– Gary Holiday2016-10-03 05:37:57 +00:00Commented Oct 3, 2016 at 5:37
-
Add your view codeSardorbek Imomaliev– Sardorbek Imomaliev2016-10-03 05:52:43 +00:00Commented Oct 3, 2016 at 5:52
Add a comment
|
4 Answers
Basically you could do this
username = request.user.username
9 Comments
Prakhar Trivedi
Seriously ? @sardorbek Why did you edit my code. I am using Camel Case type of coding. Is it really necessary to code with _ ?. There was no need.
Sardorbek Imomaliev
@PrakharTrivedi read pep8 guidlines python.org/dev/peps/pep-0008. It is convention for python community
Prakhar Trivedi
Yeah,I agree with that. But was is really necessary ? There are much better things to do than this.
Sardorbek Imomaliev
@PrakharTrivedi You are answering question of beginner python developer. It is necessary to write answer which complies with python guidlines, because he will copy and paste your code and he will think that this kind of coding style is ok, which is not for our community.
Sardorbek Imomaliev
@Addict this can be used everywhere, where
request object is passed, but usually this is done in a view |
For me, this worked as RestFrameworkJWT is no longer maintained.
So I used the rest_framework_simplejwt package.
from rest_framework_simplejwt.backends import TokenBackend
token = request.META.get('HTTP_AUTHORIZATION', " ").split(' ')[1]
try:
valid_data = TokenBackend(algorithm='HS256').decode(token,verify=True)
user = valid_data['user']
request.user = user
except ValidationError as v:
print("validation error", v)
3 Comments
validname
verifty=False - Disabling token verification is insecure, don't do this.Arpan Kushwaha
Editing the ans as suggested. @validname
рüффп
"Disabling token verification is insecure, don't do this" -> except if you just need to decode a JWT. In my case the authentication is done at another level and my backend does not have the jwt secret key. This answer is very useful.
For me with 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.
2 Comments
Jameel Mohammed
I'm getting errors can you please share ur entire middleware file
sadaf2605
Sorry, this is not what the user has asked for. But you can visit the link, it has entire middleware.
If you are using djangorestframework_simplejwt, to get user object from JWT Token you need to do the following :
token = AccessToken(access_token)
user_id = token.payload['user_id']
user = User.objects.get(id=user_id)
This works well !!
1 Comment
Abayomi Olowu
you didn't include your imports, you didnt include the access_token declaration. this response can be imporved more and better to guidd people in the future once they come accross this answer.