2

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')),
2
  • use login_required or permission_classes Commented Oct 4, 2016 at 14:19
  • Write your own permission class and use it in views. Commented Oct 4, 2016 at 14:35

1 Answer 1

4

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',
    )
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.