Granting access to other class views upon receiving JWT token Django REST

Viewed 216

Here is my API in Django REST.

Here is my code:

from rest_framework.permissions import IsAuthenticated, AllowAny

class CreateItems(generics.CreateAPIView):
    permission_classes = [IsAuthenticated]
    
    queryset = SomeModel.objects.all()
    serializer_class = SomeSerializer
    
    


class AuthStatus(APIView):

    permission_classes = [AllowAny]

    def post(self, request, *args, **kwargs):
        
        
        token = self.request.data['itemsReturnedAuthAPI']['auth-token']
        if(token):
            return Response({"Token":token})

        else:
            return Response({"message":"No Token Found!"})
   
   

I have an authentication microservice that I get the JWT Token from for the user in order to have access to the views. In the AuthStatus class I am checking the token.

My Question: I want to grant the user access to the CreateItems class, after the token is provided

1 Answers

Good question. Here are my recommendations for implementing token based authentication.

  1. Let the user send their JWT in a HTTP header for every request.

  2. Use an authentication class in rest-framework. The authentication class looks at an incoming HTTP request and determines if that request is authenticated and which user the request comes from. Most authentication classes will look at tokens in HTTP headers, then make a call to a database or microservice to validate that token. Check out the documentation. You will probably need a custom or third-party authentication class.

  3. Keep using the permission class IsAuthenticated. This class will reject unauthenticated requests.

Related