简体   繁体   中英

Getting “Authentication credentials were not provided.” message when trying to access my ModelViewSet URL

I am creating an application using Django Rest Framework and using Token based authentication. I have a PlaceViewSet class inheriting from ModelViewSet . I want both list and retrieve to work even if there is no token sent by the user whereas create, destroy and update should be allowed only if the user has sent the Token. But I am getting Authentication credentials were not provided. for requests of all types. I also want to stick to the REST standard so that the list, retrieve, update, create, destroy comes under the same model view set. In case if DRF does not allow any requests without Token if I have set my default authentication as TokenAuthentication then why I am able to access the signin and signup views?

You can change permission policy in settings.py

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny'
    ],
}

If you want to add special permissions for methods.

Permission:

from rest_framework.permissions import IsAuthenticated, IsAdminUser    

class SpecialPermissionMixin(object):

    def get_permissions(self):

        user_permission_list = ['list', 'retrieve', 'update']
        admin_permission_list = ['destroy', 'create']

        if self.action in user_permission_list:

            permission_classes = [
                IsAuthenticated,
            ]
        elif self.action in admin_permission_list:

            permission_classes = [
                IsAdminUser,
            ]
        else:
            permission_classes = []

        return [permission() for permission in permission_classes]

View:

class BlogViewSet(SpecialPermissionMixin, viewsets.ModelViewSet):
      ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM