How to set a method in Django rest framework's ViewSet to not require authentication
Asked Answered
G

1

6

I have viewset like below :

from rest_framework import viewsets
from paas.serializers import UserSerializer
import logging


logger=  logging.getLogger(__name__)

class UserViewSet(viewsets.ViewSet):
    def list(self,request):
        pass

    def create(self,request):
        logger.info(request.data)
        current_user = UserSerializer.create()

Also, I use the DRF Token based authentication in my code. How can I simply say that this create method don't require authentications? As you know after implementing authentication with the token, all request's should have Token in header's, and any request that doesn't have will get 403 error.

Gelignite answered 5/11, 2017 at 14:6 Comment(0)
R
5

Per this issue on the DRF issues tracker, the best way seems to be to create a custom permissions class. The view object has an action attribute that can be used to vary what you do in response to each sub-action for a ViewSet.

class IsCreationOrIsAuthenticated(permissions.BasePermission):

    def has_permission(self, request, view):
        if not request.user.is_authenticated():
            if view.action == 'create':
                return True
            else:
                return False
        else:
            return True

or the more detailed one from AssembledAdam

(Code copied here in line with SO policy of not just linking out, in case the link is broken or altered.)

class AnonCreateAndUpdateOwnerOnly(permissions.BasePermission):
    """
    Custom permission:
        - allow anonymous POST
        - allow authenticated GET and PUT on *own* record
        - allow all actions for staff
    """

    def has_permission(self, request, view):
        return view.action == 'create' or request.user and request.user.is_authenticated

    def has_object_permission(self, request, view, obj):
        return view.action in ['retrieve', 'update', 'partial_update'] and obj.id == request.user.id or request.user.is_staff

class ListAdminOnly(permissions.BasePermission):
    """
    Custom permission to only allow access to lists for admins
    """

    def has_permission(self, request, view):
        return view.action != 'list' or request.user and request.user.is_staff
Rolfrolfe answered 5/11, 2017 at 14:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.