Django rest framework JWT and custom authentication backend

446 views
Skip to first unread message

Robin Lery

unread,
May 26, 2017, 4:39:02 PM5/26/17
to django...@googlegroups.com
I have a custom user model and have created a custom authentication backend. I am using django rest framework JWT for token authentication.

User model:

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(
        unique=True,
        max_length=254,
    )
    first_name = models.CharField(max_length=15)
    last_name = models.CharField(max_length=15)
    mobile = models.IntegerField(unique=True)
    date_joined = models.DateTimeField(default=timezone.now)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    objects = UserManager()
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['first_name', 'last_name', 'mobile']

Auth backend:

class EmailOrMobileAuthBackend(object):
    def authenticate(self, username=None, password=None):
        try:
            user = get_user_model().objects.get(email=username)
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            if username.isdigit():
                try:
                    user = get_user_model().objects.get(mobile=username)
                    if user.check_password(password):
                        return user
                except User.DoesNotExist:
                    return None
            else:
                return None

    def get_user(self, user_id):
        try:
            return get_user_model().objects.get(pk=user_id)
        except User.DoesNotExist:
            return None
And have added in the settings.py:

AUTHENTICATION_BACKENDS = ('accounts.email_mobile_auth_backend.EmailOrMobileAuthBackend',)

While to log in to django admin site, both the email and mobile number works fine in authenticating the user. However, when I try get the token for the user using django rest framework JWT, I get an error:

curl -X POST -d "email=ad...@gmail.com&password=123123" http://localhost/api-token-auth/

"non_field_errors": [
    "Unable to log in with provided credentials."
  ]

What am I missing? Why is it that its working while loggin to the django admin site, but get error when getting token with django rest framework jwt?

Melvyn Sopacua

unread,
May 28, 2017, 11:43:55 AM5/28/17
to django...@googlegroups.com

On Saturday 27 May 2017 02:08:02 Robin Lery wrote:

 

> curl -X POST -d "email=ad...@gmail.com&password=123123"

> http://localhost/api-token-auth/

>

> "non_field_errors": [

> "Unable to log in with provided credentials."

> ]

>

> What am I missing? Why is it that its working while loggin to the

> django admin site, but get error when getting token with django rest

> framework jwt?

 

Shot in the dark: Your payload is not json.

--

Melvyn Sopacua

Reply all
Reply to author
Forward
0 new messages