JasonGenX
JasonGenX

Reputation: 5444

Django Rest Framework. Custom permission with JSONWebTokenAuthentication

I have a need to write a custom permission (deriving from BasePermission) for one of my endpoints where:

If the method is POST, it's open for everyone (e.g. returns true).. however, if the method if PUT or GET it should be authenticated with JSONWebTokenAuthentication to figure out if to clear or reject the request.

Typically, I know how to add this into my APIView class

authentication_classes = ([JSONWebTokenAuthentication])

But how do I check whether the user is already authenticated with JSONWebTokenAuthentication in case the HTTP method is PUT or GET in my Custom Permission class? Is there something like IsJSONWebTokenAuthenticated somewhere?

Upvotes: 0

Views: 1298

Answers (1)

zaidfazil
zaidfazil

Reputation: 9245

You need to write a custom permission for your view,

permissions.py

class CustomPermission(BasePermission):

    def has_permission(self, request, view):
        if (request.method =='POST' or (request.user and request.user.is_authenticated())):
            return True
        return False

Then, you need to add to your settings.py,

REST_FRAMEWORK = { 
    'DEFAULT_PERMISSION_CLASSES':
        ('rest_framework.permissions.IsAuthenticated', ),
    'DEFAULT_AUTHENTICATION_CLASSES':
        ('rest_framework_jwt.authentication.JSONWebTokenAuthentication',
         'rest_framework.authentication.SessionAuthentication',
         'rest_framework.authentication.BasicAuthentication', ),
         }

Then add the permission to your permission_classes of the view,

from .permissions import CustomPermission

class YourView(APIView):
    permission_classes = (CustomPermission, )

Upvotes: 1

Related Questions