Reputation: 7410
So I have a function based view that I am using along with Django rest framework which looks like this :
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import permission_classes
@api_view(['GET'])
@permission_classes((IsAuthenticated, ))
def example_view(request):
.....
<business logic>
.....
This works as expected and gives a HTTP 401 if a user with insufficient privileges tries to access a URL bound to this view .However,due to how the front end angular is set up,what I need is to display a HTTP_403(forbidden).I went through the DRF documentation and could not see any already defined permission class that I can use as a decorator..What would be the best way of implementing this ?
Upvotes: 4
Views: 7291
Reputation: 7410
So I found a solution to this.The IsAuthenticated class has very specific rules about emitting a 401 versus a 403 and they are as follows:
- The request was successfully authenticated, but permission was denied. — An HTTP 403 Forbidden response will be returned.
- The request was not successfully authenticated, and the highest priority authentication class does not use WWW-Authenticate headers. — An HTTP 403 Forbidden response will be returned.
- The request was not successfully authenticated, and the highest priority authentication class does use WWW-Authenticate headers. — An HTTP 401 Unauthorized response, with an appropriate WWW-Authenticate header will be returned.
So inorder to force DRF to emit a 403 always just use an authentication class which does not use WWW-Authenticate headers.This is what i finally ended up with :
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import permission_classes
from rest_framework.decorators import authentication_classes
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
@api_view(['GET'])
@authentication_classes((SessionAuthentication, BasicAuthentication))
@permission_classes((IsAuthenticated, ))
def example_view(request):
.....
<business logic>
.....
Upvotes: 5