简体   繁体   中英

Restrict Django Rest Framework for all users except super users

Can I restrict my Django Rest Framework to be only accessed by super users?

Can I add a decorator to the urls so that the url is only accessed by super users:

url(r'^api/', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),

If you want to allow any staff member to access the API, then it's easy

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAdminUser',
    )
}

For super user, there isn't a built in permissions class, but we can make one easily.

from rest_framework import permissions

class SuPermission(permissions.BasePermission):

    def has_permission(self, request, view):
        return request.user.is_authenticated() and request.user.is_superuser

and then

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'myapp.permissions.SuPermission',
    )
}

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