I am using djangorestframework-simplejwt to configure authentication for my django app. I have configured a login view to authenticate a user with an email and password and I have a login endpoint to test if it is working correctly.
When I log in a user with email and password, I am successfully logged in and an access token which could be used to maintain the session is generated. Problem is, after the token has expired, I am getting an invalid credentials error even though the email and password are correct.
I suspect that the authenticate object is returning None for some reason after the token has expired or I may have configured simplejwt incorrectly.
Below is my login view
class login_view(APIView):
"""Logs in a user"""
authentication_classes = [JWTAuthentication]
def post(self, request):
target_email = os.environ.get('TARGET_EMAIL')
email = request.data.get('email')
password = request.data.get('password')
if email != target_email:
return Response({'error': 'Invalid email'}, status=status.HTTP_401_UNAUTHORIZED)
user = authenticate(request, email=email, password=password)
if user is not None:
login(request, user)
# Generate Access Token and Refresh Token
refresh = RefreshToken.for_user(user)
access_token = str(refresh.access_token)
refresh_token = str(refresh)
#jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
#jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
#payload = jwt_payload_handler(user)
#token = jwt_encode_handler(payload)
return Response({'access_token': access_token, 'refresh_token': refresh_token})
else:
return Response({'error': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED)
My simplejwt config
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
# 'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}
from datetime import timedelta
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=4),
'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
}
My user model
# Create your models here.
class CustomUserManager(BaseUserManager):
"""An admin user manager"""
def create_user(self, email, password=None, **extra_fields):
"""Creates a standard user using email"""
if not email:
raise ValueError("Email field should be set")
email = email.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
"""def create_superuser(self, email, password=None, **extra_fields):
Creates an admin user
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError("Superuser must have is_staff=True")
if extra_fields.get('is_superuser') is not True:
raise ValueError("Superuser must have is_superuser=True")
return self.create_user(email, password, **extra_fields)"""
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
is_active = models.BooleanField(default=True)
#is_staff = models.BooleanField(default=True)
#date_joined = models.DateTimeField(default=timezone.now)
objects = CustomUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
def __str__(self):
return self.email
I commented out some code. Check only the uncommented code thanks
In the login view, I tried inserting the code user = authenticate(request, email, password)
to see if that will allow for reaunthication. Also, I set is.active()
to True in the user model. Currently, the only way I can log in successfully is if I reset a user's password