jpadilla / django-rest-framework-jwt

JSON Web Token Authentication support for Django REST Framework
http://jpadilla.github.io/django-rest-framework-jwt/
MIT License
3.19k stars 652 forks source link

DRF JWT [non_field_errors: 'Invalid payload.'] on custom payload handlers #375

Closed ebotean closed 7 years ago

ebotean commented 7 years ago

I have had an issue related to custom payload handlers. My Django User Model uses the user email as the means of authentication (i.e. username).

Therefore, as I have concluded, you must have a method that overrides the default username field to 'email'.

Just for clarification for those looking for an answer in the future, I have managed to solve it. The problem lied at the payload handlers. I had overwritten the payload and response payload handlers respectively in such way:

def jwt_payload_handler(user): return { 'user_id': user.pk, <<<<'email': user.email,>>>> 'is_cidadao': user.is_cidadao, 'is_politico': user.is_politico, 'exp': datetime.utcnow() + api_settings.JWT_EXPIRATION_DELTA, 'orig_iat': timegm( datetime.utcnow().utctimetuple() ) }

def jwt_response_payload_handler(token, user=None, request=None): return { 'token': token, <<<< 'email': user.email,>>>> 'is_cidadao': user.is_cidadao, 'is_politico': user.is_politico, }

OTHERWISE, it is possible to fix this by declaring the 'username' field on the first level (outside any objects) of the payload handlers. Notice the email field in bold, it should, therefore be changed to

def jwt_payload_handler(user): return { 'user_id': user.pk, <<<<'username': user.email,>>>> 'is_cidadao': user.is_cidadao, 'is_politico': user.is_politico, 'exp': datetime.utcnow() + api_settings.JWT_EXPIRATION_DELTA, 'orig_iat': timegm( datetime.utcnow().utctimetuple() ) }

def jwt_response_payload_handler(token, user=None, request=None): return { 'token': token, <<<<'username': user.email,>>>> 'is_cidadao': user.is_cidadao, 'is_politico': user.is_politico, }

I have solved this using feedback given in issues #284 and #145.

blueyed commented 7 years ago

Closing as duplicate of #284 then. Thanks for reporting back. Over there a possible solution was mentioned.. wanna give this a try?

bachrc commented 5 years ago

@ebotean Thanks a lot for your feedback on this issue, I was lost because of this message ! Thank you !