In my django rest app i like to change the default error response from JWTAuthentication. Currently my application is using JWT With django to work on login and logout (which blacklists the token). Below is my code.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
)
}
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import RefreshToken, BlacklistMixin
class BlacklistRefreshTokenView(APIView, BlacklistMixin):
def post(self, request):
token = RefreshToken(request.data.get('token'))
token.blacklist()
# return Response({'message': 'Token blacklisted successfully.'})
return json_response('Logout successful', None, 200)
class CustomTokenObtainPairView(TokenObtainPairView):
def post(self, request, *args, **kwargs):
# Call the base class's post method to continue with the login process
response = super().post(request, *args, **kwargs)
return response
from django.urls import path
from .views import CustomTokenObtainPairView, BlacklistRefreshTokenView
urlpatterns = [
path('login/', CustomTokenObtainPairView.as_view(), name="login"),
path('logout/', BlacklistRefreshTokenView.as_view(), name='blacklist_token'),
]
{
"detail": "Given token not valid for any token type",
"code": "token_not_valid",
"messages": [
{
"token_class": "AccessToken",
"token_type": "access",
"message": "Token is invalid or expired"
}
]
}
{
"message": "Given token not valid for any token type",
"status": "401"
}
So, I was able to achieve the same by following exception topics in Django rest framework. So, to have our custom exception response for every single response in our Django project, we need to update the REST_FRAMEWORK
field in the project's settings.py
file. An example below:
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}