permission classes IsAuthenticated not working in DRF

user10058776 picture user10058776 · Dec 8, 2018 · Viewed 7.6k times · Source

I've used token authentication, and it's working fine i.e. it is authenticating a user and then the user is logged in. But in my views I've set permission classes to IsAuthenticated for one of the views, and it is not allowing to the user even if he is an authenticated user. Below is the screenshot where it says i'm logged in ([email protected]) :

enter image description here

and the very next tab to this, it says "authentication details not provided":

enter image description here

Can someone tell what's wrong? ok, I'm providing details: these are my settings:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated', )
}

This is how I authenticated:

class UserLoginAPIView(APIView):

permission_classes = [AllowAny]
serializer_class = UserLoginSerializer

def post(self, request, *args, **kwargs):
    data = request.data
    serializer = UserLoginSerializer(data=data)
    if serializer.is_valid(raise_exception=True):
        # new_data = serializer.data
        if serializer.data:
            user = authenticate(username=request.data['username'], password=request.data['password'])
            login(request, user)
            print("IsAuthenticated", user.is_authenticated)
        token, _ = Token.objects.get_or_create(user=user)
        return Response({'token': token.key},
                        status=HTTP_200_OK)

Another View where I put restrictions:

class BoardCreateAPIView(CreateAPIView):

queryset = Boards.objects.all()
serializer_class = BoardCreateSerializer
permission_classes = (IsAuthenticated,)

Answer

Reza Torkaman Ahmadi picture Reza Torkaman Ahmadi · Dec 8, 2018

In django rest framework, You should provide token in your request headers. here is the sample with curl command:

curl -X POST -H "Content-Type: application/json" -H "Authorization: Token <MY_TOKEN>" http://my-api-url

Also check that in your settings.py at least you have these lines:

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.BasicAuthentication',
    'rest_framework.authentication.SessionAuthentication',
)
}

For more understanding read this doc from django rest framework