3👍
✅
You can get the token, userid and username by following these steps:
Inside your app
, create a utils.py
file (at the same level where serializers.py is placed).
Content of utils.py
:
from .serializers import UserSerializer #you have already created UserSerializer
def jwt_response_payload_handler(token, user=None, request=None):
user = UserSerializer(user, context={'request': request}).data
return {
'token': token,
'userid': user['id'],
'username':user['username']
}
In your settings.py
, add
JWT_AUTH = {
'JWT_RESPONSE_PAYLOAD_HANDLER':
'app_name.utils.jwt_response_payload_handler', #app_name is name of the app which contains utils.py
}
Now when you hit the api (api-token-auth/) to get the token, it will respond with token, userid and username.
Example of response:
{
'token':'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImdhbmVzaG5lZ2lAZ21haWwuY29tIiwiZXhwIjoxNTI0NTAyNzIzLCJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6ImdhbmVzaG5lZ2kifQ.RxnYF1gwaYywSnnWC-ngrcZaw90lpD6Rq7jcbnEoZVk',
'userid':1,
'username':'ganeshnegi'
}
1👍
According to the django-rest-framework-jwt
docs this view only returns the username and password (emphasis mine).
In your urls.py add [
url(r'^api-token-auth/', obtain_jwt_token)
] to enable obtaining a token via a POST included the user’s username and password.
I wouldn’t worry about not obtaining the id, you should be able to query the User table by username.
- [Django]-DRF SessionAuthentication login page insecurity?
- [Django]-Get minimum of related model date field (django)
- [Django]-Python/Django date field in html input tag
Source:stackexchange.com