Search code examples
djangorestdjango-rest-frameworkjwtdjango-rest-framework-simplejwt

Expired access token accepted and return the data from view in django


I'm creating an app that sends both a refresher and access tokens; also, in this app, there are a ModelViewSet called Users (returns all users in the database) where permission_classes for the IsAuthenticated only, everything seems to work perfectly.

But when the access token expires and sets the header for the Authentication = 'Bearer ${access_token},' the ModelView returns the data despite the expiration of the access_token, and checks the same token with the TokenVerifyView, its returns:

{
    "detail": "Token is invalid or expired",
    "code": "token_not_valid"
}

I'm using rest_framework and rest_framework_simplejwt the ACCESS_TOKEN_LIFETIME equal to 10sec and the DEFAULT_AUTHENTICATION_CLASSES are the default from the lib itself

class UserViewSet(ModelViewSet):
    permission_classes = [permissions.IsAuthenticated,]
    queryset = User.objects.all()
    serializer_class = UserSerializer
REST_FRAMEWORK = {
    
    'DEFAULT_AUTHENTICATION_CLASSES': (
        
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    )
    
}
SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(seconds=10),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
    'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': False,
    'UPDATE_LAST_LOGIN': False,

    'ALGORITHM': 'HS256',
    'SIGNING_KEY': SECRET_KEY,
    'VERIFYING_KEY': None,
    'AUDIENCE': None,
    'ISSUER': None,
    'JWK_URL': None,
    'LEEWAY': 0,

    'AUTH_HEADER_TYPES': ('Bearer',),
    'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
    'USER_ID_FIELD': 'id',
    'USER_ID_CLAIM': 'user_id',
    'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule',

    'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
    'TOKEN_TYPE_CLAIM': 'token_type',
    'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser',

    'JTI_CLAIM': 'jti',

    'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
    'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
    'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}

Should I create an authentication class and add it to the DEFAULT_AUTHENTICATION_CLASSES, or is there a predefined way to handle this problem, so if the token is expired, return status with 403


Solution

  • I just needed to upgrade the djangorestframework-simplejwt to the latest version, I had 5.2.1, and I upgraded it to 5.2.2.