Login

Django Rest Framework LoginExemptPermission: Apply `IsAuthenticated` to all ViewSet actions except those specified as exempt of authentication

Author:
AgustinLado
Posted:
October 18, 2016
Language:
Python
Version:
Not specified
Score:
0 (after 0 ratings)

Say you want to keep your API secure and thus it has authentication, but there's this one View action in a ViewSet which unlike the rest of the ViewSet's actions needs to allow free access without authentication.

This solution applies the good old IsAuthenticated permission to all ViewSet actions except those defined in a login_exempt_actions list. That's a list of the ViewSet action's names.

This is a simple solution for this particular problem, which I imagine could be quite common. Any case where the requirements are more complex should implement one of the DRF permissions extensions which allow for the use of logical operators.

NOTE: Remember that request.user will be an AnonymousUser instance, so be careful with any code which assumes it'll be a User instance. This could be the case with, say, a custom get_queryset implementation.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from rest_framework import permissions


class LoginExemptPermission(permissions.BasePermission):
    """
    Applies the DRF `IsAuthenticated` permission to all ViewSet actions except
    those defined in the ViewSet attribute `login_exempt_actions`.
    """
    def has_permission(self, request, view):
        if view.action in view.login_exempt_actions:
            return True
        return permissions.IsAuthenticated().has_permission(request, view)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.