django-rest-framework icon indicating copy to clipboard operation
django-rest-framework copied to clipboard

use USERNAME_FIELD instead username in generate token for user in token authentication

Open mojtabaakbari221b opened this issue 2 years ago • 4 comments

Imagine a situation where someone has chosen email as the USERNAME_FIELD field, with the current logic, it is only possible to create a token by sending the username, but if it is possible to create a token for the USERNAME_FIELD field, it is possible to create a token for any other USERNAME_FIELD field such as mobile number or email.

This idea is taken from the djoser package and has an interesting implementation. Also I can add this feature to drf. Is it worth the time to merge with the package?

mojtabaakbari221b avatar Jan 11 '23 10:01 mojtabaakbari221b

can you share the code snippet please?

auvipy avatar Jan 11 '23 10:01 auvipy

file

In the AuthTokenSerializer class we have:

username = serializers.CharField(
         label=_("Username"),
         write_only=True
     )

If you can write as below, you can have the same capabilities as I said:

class AuthTokenSerializer(serializers.Serializer):
    ...
    def __init__(self, *args, **kwargs):
        self.fields[User.USERNAME_FIELD] = serializers.CharField()

Of course, some other changes are needed elsewhere, but that's the general idea. I don't know if I was able to convey my meaning or not.

mojtabaakbari221b avatar Jan 11 '23 12:01 mojtabaakbari221b

I think this is a near duplicate of https://github.com/encode/django-rest-framework/pull/4193.

My understanding was that you could pass whatever the USERNAME_FIELD value is as username within the view and it would map appropriately because of how the Django authenticate method works.

kevin-brown avatar Jan 14 '23 18:01 kevin-brown

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Mar 18 '23 08:03 stale[bot]