I'm finding hard to figure out how to return 401 when the token has been deleted in database for whatever reason.
Let me explain.
My general settings use SessionAuthentication and TokenAuthentication schemes.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_FILTER_BACKENDS': (
'rest_framework.filters.DjangoFilterBackend',
),
'DATETIME_FORMAT': '%a, %d %b %Y %H:%M:%S %z',
'DATETIME_INPUT_FORMATS': ['iso-8601', '%Y-%m-%d %H:%M:%S', '%a, %d %b %Y %H:%M:%S %z'],
'DATE_FORMAT': '%Y-%m-%d',
'DATE_INPUT_FORMATS': ['%Y-%m-%d', '%m/%d/%YYYY'],
'PAGE_SIZE': 20
}
I have a view for generating the Auth Token, like this:
class AcmeObtainAuthToken(APIView):
throttle_classes = ()
permission_classes = ()
parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,)
renderer_classes = (renderers.JSONRenderer,)
serializer_class = AcmeAuthTokenSerializer
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data)
serializer.context = {'request': self.request}
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
return Response({'token': token.key,
'school': school,
'user': user.id})
obtain_auth_token = AcmeObtainAuthToken.as_view()
My problem is that when token stored in db is gone for whatever reason and clients send the token, I'm getting 403, when I require 401.
Looking at the docs this is really cryptic:
The kind of response that will be used depends on the authentication scheme. Although multiple authentication schemes may be in use, only one scheme may be used to determine the type of response. The first authentication class set on the view is used when determining the type of response.
It says it depends but how? No example is given...kinda confusing on how DRF does its magic under the hood here...