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]) :
and the very next tab to this, it says "authentication details not provided":
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,)
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