How to add django rest framework permissions on specific method only ?

别来无恙 提交于 2019-11-29 03:57:06

You can write a custom Permission class IsPostOrIsAuthenticated which will allow unrestricted access to POST requests but will allow only authenticated GET requests.

To implement the custom permission IsPostOrIsAuthenticated, override the BasePermission class and implement .has_permission(self, request, view) method. The method should return True if the request should be granted access, and False otherwise.

from rest_framework import permissions

class IsPostOrIsAuthenticated(permissions.BasePermission):        

    def has_permission(self, request, view):
        # allow all POST requests
        if request.method == 'POST':
            return True

        # Otherwise, only allow authenticated requests
        # Post Django 1.10, 'is_authenticated' is a read-only attribute
        return request.user and request.user.is_authenticated

So, all POST requests will be granted unrestricted access. For other requests, authentication will be required.

Now, you need to include this custom permission class in your global settings.

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'my_app.permissions.IsPostOrIsAuthenticated',
    )
}

http://www.django-rest-framework.org/api-guide/permissions/

as per above URL you have to write one custom permission class

class ExampleView(APIView):
    permission_classes = (MyCUstomAuthenticated,)

Write your own logic using AllowAny or IsAuthenticated inside MyCUstomAuthenticated based on POST and GET

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!