Saqib Ali
Saqib Ali

Reputation: 12605

How are permissions to access to Django REST API managed?

I am building a Django application that exposes a REST API by which users can query my application's models. I'm following the instructions here.

Below you can see me hitting this API from the command line with various username/passwords. However, it only works If I use the root user and password. Why? How do I change that? I have not specified anywhere that this API is only available to the root user. I want it to be publicly available

% curl -H 'Accept: application/json; indent=4' -u root:myRootPassword http://127.0.0.1:3001/api/profiles/60/
{
    "id": 60,
    "slug": "my_user",
    "user": "http://127.0.0.1:3001/api/users/16/"
}

% curl -H 'Accept: application/json; indent=4' http://127.0.0.1:3001/api/users/16/
{
    "detail": "Authentication credentials were not provided."
}

% curl -H 'Accept: application/json; indent=4'  -u myUser:myPassword http://127.0.0.1:3001/api/profiles/60/
{
    "detail": "You do not have permission to perform this action."
}

% curl -H 'Accept: application/json; indent=4'   -u myUser:myPassword http://127.0.0.1:3001/api/profiles/60/
{
    "detail": "Invalid username/password"
}

Upvotes: 4

Views: 6486

Answers (1)

user133688
user133688

Reputation: 7064

In your APIView, or your ModelViewSet do

permission_classes = []

or

permission_classes = [rest_framework.permissions.AllowAny]

This will make it publicaly available for any one. This is because all modeviewsets/viewsets/ or APIViews all inheirit from APIView which sets the permission classes to

permission_classes = api_settings.DEFAULT_PERMISSION_CLASSES

Which I'm guessing in your case is only a superuser.

OK Just looked at the guide you're following. If you look at your settings

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

Your setting the default permission class to be only admins. So you can either do what I suggested earlier and override the default permissions, or change IsAdminUser to

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.AllowAny',),
    'PAGINATE_BY': 10
}

Good luck, django-rest-framework is amazing.

Upvotes: 5

Related Questions