Search code examples
djangodjango-rest-frameworkjwtdjango-rest-framework-jwt

How to add a django rest framework authentication in Route?


How to add a django rest framework authentication in Route?

I am using JWT for authentication of my application. Everything works perfectly.

What I need to know is how can I authenticate a particular Route based on REST Framework and JWT

example

from rest_framework.permissions import IsAuthenticated

path(r'modulo/app/aula/<modalidade>', IsAuthenticated  AppAulaAdd.as_view(),     name='app_aula')

or

from rest_framework.decorators import authentication_classes

path(r'modulo/app/aula/<modalidade>',  authentication_classes(AppAulaAdd.as_view()),     name='app_aula')

Both does not work.


Solution

  • You're mixing concepts in your question. Permission classes control access to resources based on the status of the user in your system or in a session (i.e. IsAuthenticated, IsStaff, etc), while authentication classes control the method to authenticate the user, for example BasicAuthentication or in your case JSONWebTokenAuthentication. Also, you should add both types of classes directly in your views, it's better practice (from https://www.django-rest-framework.org/api-guide/authentication/):

    class ExampleView(APIView):
        authentication_classes = (SessionAuthentication, BasicAuthentication)
        permission_classes = (IsAuthenticated,)
    

    But if for some reason it's 100% necessary to add the permission in your urls file (routes), you can do the following:

    from rest_framework.decorators import permission_classes
    from rest_framework.permissions import IsAuthenticated
    
    path(r'modulo/app/aula/<modalidade>', (permission_classes([IsAuthenticated])(AppAulaAdd)).as_view(), name='app_aula')
    

    Hope it helps.