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

21👍

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_settings
from datetime import datetime


jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

my_user = User.objects.get(pk=1) # replace with your existing logic

payload = jwt_payload_handler(my_user)

# Include original issued at time for a brand new token,
# to allow token refresh
if 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.

Leave a comment