Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST difference between permission classes and authentication classes

There is one last thing I'm a little confused on with Django Rest Framework and that's the different between permission classes and authentication classes.

this is my settings.py

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


),
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
    'rest_framework.authentication.SessionAuthentication',
),
'PAGINATE_BY': 10

}

and in my view I have the following...

class ProfileList(generics.ListCreateAPIView):
    """
    API endpoint that represents a list of users.
    """
    permission_classes = (permissions.IsAdminUser,)
    model = Profile
    serializer_class = ProfileSerializer

    def pre_save(self, obj):
        obj.owner = self.request.user

What I assumed would happen with above is that only admin users had access to the browserable API while still a user with a valid token could get the json request. However, this is not the case only is IsAuthenticated seems to give them access but = this and still allows my users access to the online version when logged in.

I want all my users with a valid token to get access, but only admin users to have permission to view the online API version with sessions, is this possible?

like image 245
Prometheus Avatar asked Feb 14 '13 17:02

Prometheus


2 Answers

I want all my users with a valid token to get access, but only admin users to have permission to view the online API version with sessions, is this possible?

The first thing worth noting is that the browseable API won't give your users any more permissions than they would having if you only render to JSON. It's just a much nicer view onto the API endpoints. Personally I would typically want to expose the browseable API to end-developers as it makes developing against the API easier.

If you really do want to hide it from everyone except admin users here are two approaches you could take:

  1. Override the get_renderers() method on the view. (Briefly documented here) You can check self.request.user.is_staff, and only include the Browseable API renderer if it's an admin user.

  2. Subclass the browseable API renderer, and override .render(). (Eg see here) You can get the incoming request using renderer_context['request'], and simply render to standard JSON if it's not an admin user.

like image 58
Tom Christie Avatar answered Sep 30 '22 01:09

Tom Christie


I think it works as described in the docs:

If any permission check fails an exceptions.PermissionDenied exception will be raised, and the main body of the view will not run.

If you set IsAdminUser, the user has to be an admin. Or else he wont have permission, even if all things that are required in DEFAULT_AUTHENTICATION_CLASSES are provided.

like image 21
webjunkie Avatar answered Sep 30 '22 03:09

webjunkie