Search code examples
djangodjango-rest-frameworkjwtapi-keydjango-rest-framework-simplejwt

Custom permissions for Simple-JWT in Django Rest Framework


For my current system, I am using Simple-JWT as my user authentication. And also using Django REST Framework API Key. I am satisfied with Simple-JWT for its simplicity. However, I would like to add a permission where it requires my Api-Key to be able to view the token page.

As for now, if I want to get a JWT Token,

I can simply go to /project/api/token/ (To get access and refresh token)

OR

/project/api/refresh/ (To refresh the access token)

In my settings.py file, I have set the DEFAULT_AUTHENTICATION_CLASSES and DEFAULT_PERMISSION_CLASSES. From my understanding, if I put 'HasAPIKey' as the default permission classes, all pages will require the Api-Key.

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework_simplejwt.authentication.JWTAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework_api_key.permissions.HasAPIKey',
),
}

However both /token/ and /refresh/ can still be accessed without an Api-Key. Hence, my goal is to make sure those URLs require my Api-Key.

(Note: I am fully satisfied with how 'simple-jwt' provides the token. It was easy to be implemented. I simply want to add the 'HasAPIKey' permission)


Solution

  • Create a new view and inherit the views from rest_framework_simplejwt. Create functions for both TokenObtainPairView and TokenRefreshView. Insert those two views into the parameter for the custom view. Only then insert the permission class. As of now I want my custom views to only be accessed with the valid API Key.

    views.py

    from rest_framework_simplejwt.views import(
    TokenObtainPairView,
    TokenRefreshView,
    )
    
    class NewTokenObtainPairView(TokenObtainPairView):
         permission_classes = (HasAPIKey,)
    
    class NewTokenRefreshView(TokenRefreshView):
         permission_classes = (HasAPIKey,)