How to do Django JSON Web Token Authentication without forcing the user to re-type their password? How to do Django JSON Web Token Authentication without forcing the user to re-type their password? django django

How to do Django JSON Web Token Authentication without forcing the user to re-type their password?


When working with Django REST Framework JWT, it is typically expected that the user is generating the token on their own. Because you are generating the token on behalf of the user, you can't use any of the standard views to make it work.

You are going to need to generate the token on your own, similar to how DRF JWT does it in the views. This means using something like the following for your view code

from rest_framework_jwt.settings import api_settingsfrom datetime import datetimejwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLERjwt_encode_handler = api_settings.JWT_ENCODE_HANDLERmy_user = User.objects.get(pk=1) # replace with your existing logicpayload = jwt_payload_handler(my_user)# Include original issued at time for a brand new token,# to allow token refreshif api_settings.JWT_ALLOW_REFRESH:    payload['orig_iat'] = timegm(        datetime.utcnow().utctimetuple()    )return {    'token': jwt_encode_handler(payload)}

This should allow you to manually generate the token within the view, without having to know the user's password.