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.
settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
)
}
account app views.py
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
urls.py
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'),
]
response im getting when token is invalid
{
"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"
}
]
}
expected response
{
"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_FRAMEWORKfield in the project'ssettings.pyfile. An example below: