0
votes

I have followed all the instructions specified at Django REST framework JWT. But when I use my custom user model for login, it doesn't work.

settings.py

...

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    ),
}

Custom user manager:

class UserManager(BaseUserManager):
    def create_user(self, email, password=None, **kwargs):
        if not email:
            raise ValueError('Users must have a valid email address.')

        user = self.model(
            email=self.normalize_email(email), full_name=kwargs.get('full_name')
        )

        user.set_password(password)
        user.save()

        return user

    def create_superuser(self, email, password, **kwargs):
        user = self.create_user(email, password, **kwargs)
        user.is_admin = True
        user.save()

        return user

Here is my views.py which I am using for login:

class LoginView(views.APIView):
    def post(self, request, format=None):
        data = json.loads(request.body)

        email = data.get('email', None)
        password = data.get('password', None)

        account = authenticate(email=email, password=password)

        if account is not None:
            if account.is_active:
                login(request, account)
                serialized = UserSerializer(account)
                return Response(serialized.data)
            else:
                return Response({
                    'status': 'Unauthorized',
                    'message': 'This account has been disabled.'
                }, status=status.HTTP_401_UNAUTHORIZED)
        else:
            return Response({
                'status': 'Unauthorized',
                'message': 'Username/password combination invalid.'
            }, status=status.HTTP_401_UNAUTHORIZED)
3
What is the error displayed to you? What isn't working about it? - jape
There's no error. Everything is working like its not configured. - Puneet
Did you check your installed apps? - Jeff T
Yes, also its working for the default login DRF login API (api-token-auth). - Puneet
By default the token should be returned on a request to POST /api-token-auth/. How do you try to obtain the token? - iulian

3 Answers

0
votes

Check installed apps:

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_extensions',
    'rest_framework',
)
0
votes

The whole point of JWT (JSON Web Token) authentication is the token that is being generated using a specific algorithm.

For your LoginView to work properly, you need to:

  1. authenticate a user
  2. generate a JWT token by using the rest_framework_jwt.utils.jwt_encode_handler method
  3. add the generated token to the response payload

You can check out the source code of the DRF-JWT module to see how this is done, but unless you want to substantially modify the response payload (by including, for instance a serialized representation of a model that is unrelated to the User model), I would recommend you use the implicit authentication and adjusting the behavior with the existing module API.

0
votes

if you use the django rest framework authtoken

you can do this

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    ),
}