1

I understand that we can set up authentication classes in class based viewsets like this:

class ExampleViewSet(ModelViewSet):
    authentication_classes = (SessionAuthentication, BasicAuthentication)

However, is there a way to dynamically change the authentication class based on the request method? I tried overriding this function in my ExampleViewSet:

def get_authenticators(self): # Found in 
    if self.request.method == "POST":
        authentication_classes.append(authentication.MyCustomAuthentication)
    return authentication_classes

However, django rest does not have the request object setup at this point:

'ExampleViewSet' object has no attribute 'request'

Note: not real variable names - just for example purpose.

Apoorv Kansal
  • 3,210
  • 6
  • 27
  • 37

2 Answers2

2

Based on the previous answer, it works on django 1.10

@detail_route(methods=['post', 'get'])
def get_authenticators(self):
    if self.request.method == "GET":
        self.authentication_classes = [CustomAuthenticationClass]
    return [auth() for auth in self.authentication_classes]
andre
  • 192
  • 2
  • 12
1

You can use detail_route decorator from rest_framework like this for getting requests, detail_route can be used to define post as well as get,options or delete options So,the updated code should be like :

from rest_framework.decorators import detail_route

class ExampleViewSet(ModelViewSet):
    authentication_classes = (SessionAuthentication, BasicAuthentication)

    @detail_route(methods=['post','get'])
    def get_authenticators(self, request, **kwargs): # Found in 
        if request.method == "POST":
            authentication_classes.append(authentication.MyCustomAuthentication)
        return authentication_classes

For further reading,Read from here.

Prakhar Trivedi
  • 8,218
  • 3
  • 28
  • 35
  • 1
    using django 1.11 with python3 it says get_authentictors is expecting 2 arguments but only received one (which makes sense since this override specifies self and request as positional args). I think for my use case https://stackoverflow.com/questions/19773869/django-rest-framework-separate-permissions-per-methods seems to get me what I'm looking for. – lbrindze Aug 30 '17 at 18:16