ron
ron

Reputation: 151

Django rest framework API permission

I would like to limit the access to myweb/api in Django rest framework.

I've tried:

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

But it limits all the requests however I want to limit access only to myweb/api page.

Upvotes: 2

Views: 4141

Answers (1)

click
click

Reputation: 2113

You could add liberal permissions in settings.py file and add more restrictive ones in the specific api view.

In settings.py, add something like :

'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
),

of you could also use AllowAny permission.

You can set the authentication policy on a per-view, or per-viewset basis, using the APIView class based views.

from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

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

    def get(self, request, format=None):
        content = {
            'status': 'request was permitted'
        }
        return Response(content)

Or, if you're using the @api_view decorator with function based views.

from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

@api_view('GET')
@permission_classes((IsAuthenticated, ))
def example_view(request, format=None):
    content = {
        'status': 'request was permitted'
    }
    return Response(content)

When you set new permission classes through class attribute or decorators you're telling the view to ignore the default list set over the settings.py file.

Upvotes: 5

Related Questions