Search code examples
authenticationpermissionsdjango-rest-frameworkauthorizationdjango-rest-framework-jwt

how to use django REST JWT authorization and authentication in class based views


I am using JWT authentication I am using this type of authorization app wide.

I am trying to figure out how to ue it in a view.

Example. Say I only want to allow a user to create an approved venue if they have the correct permissions. What would I add to this view to get access to the user?

I know that django has request.user but how do I turn that on? Is it always on and request.user is null if there is no token passed into the header? Or is it middleware? The problem I am ultimately having is there is a lot of info getting to this point, but very little on actually using the JWT on the view.

please help.

# for creating an approved venue add ons later
class CreateApprovedVenue(CreateAPIView):
    queryset = Venue.objects.all()
    serializer_class = VenueSerializer

Django rest framework jwt docs https://jpadilla.github.io/django-rest-framework-jwt/

Django rest framework permissions docs http://www.django-rest-framework.org/api-guide/permissions/

so I discovered this resource and looking at it now. https://code.tutsplus.com/tutorials/how-to-authenticate-with-jwt-in-django--cms-30460

This example is sheading light:

# users/views.py
class CreateUserAPIView(APIView):
    # Allow any user (authenticated or not) to access this url 
    permission_classes = (AllowAny,)

    def post(self, request):
        user = request.data
        serializer = UserSerializer(data=user)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)

Solution

  • To use JWT authentication, you need to do the following installation steps: https://jpadilla.github.io/django-rest-framework-jwt/#installation

    Once that is done, you can include the auth by simply adding the authentication_classes as follows

    # for creating an approved venue add ons later
    class CreateApprovedVenue(CreateAPIView):
        authentication_classes = (JSONWebTokenAuthentication, )
        queryset = Venue.objects.all()
        serializer_class = VenueSerializer
    

    And you have user available to you as request.user in all the request methods. In the case of the CreateAPIView you can do:

    def post(self, request, *args, **kwargs):
        user = request.user
        ...