I am using a django-simplejwt and I have a custom token view for obtaining token. My problem is, how can i override the 401 Unauthorized response from the view?
CodePudding user response:
The answer might resides in the Exception raised.
As you dive in the simplejwt package you'd see something as following :
class InvalidToken(AuthenticationFailed):
status_code = status.HTTP_401_UNAUTHORIZED
default_detail = _('Token is invalid or expired')
default_code = 'token_not_valid'
This is where comes from the 401 you see.
Therefore your class ObtainToken
should override the post method from the mother class TokenViewBase
with you specific Exception
or Response
.
For example :
from rest_framework import status
...
class ObtainToken(TokenObtainPairView):
serializer_class = ObtainTokenSerializer
...
def post(self, request):
serializer = self.serializer_class(
data=request.data,
context={'request': request}
)
try:
serializer.is_valid()
return Response(
serializer.validated_data,
status=status.HTTP_200_OK
)
except Exception:
return Response(status=status.HTTP_404)
Although above is just an example, you should implement something similar as the post method from TokenViewBase
but with your customized status and data.