Search code examples
pythondjangodjango-rest-frameworkdjango-rest-auth

DJANGO REST API - How do I restrict user access to API?


So I’ve been putting together a REST API using William Vincent’s REST API’s with Django book. I have everything up and going according to the book but I’m a bit of a noob so I need some clarification from the pros.

How can I restrict a user with a token to see certain information within my API?

Created user with Token: enter image description here

i added authentication_classes = [TokenAuthentication] to class UserList thinking if a user is logged in with a token that logged in user would be able to access that information of my api but I get the below:

enter image description here

When I remove authentication_classes = [TokenAuthentication], I get the below.

enter image description here

All users are able to see my API and I don’t want that, I only want users with a Token to view my api.

Any help is gladly appreciated!

Thanks! Code below

# api/views.py

from django.contrib.auth import get_user_model

from rest_framework import generics, permissions
from rest_framework.authentication import TokenAuthentication
from .serializers import UserSerializer

# Display List View - User
class UserList(generics.ListAPIView):
    queryset = get_user_model().objects.all()
    serializer_class = UserSerializer
    permission_classes = (permissions.IsAuthenticated,)
    authentication_classes = [TokenAuthentication]

# api/serializers.py

from django.contrib.auth import get_user_model
from rest_framework import serializers

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = get_user_model()
        fields =('id', 'username', 'email',)

#api/urls.py

from django.urls import path
from .views import  (UserList)

urlpatterns = [
    path('users/', UserList.as_view()),    
]

#master_application/urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('users.urls')),
    path('api/', include('api.urls')),
    path('api-auth/', include('rest_framework.urls')),
    path('api/rest-auth/', include('rest_auth.urls')),
    path('api/rest-auth/registration/', include('rest_auth.registration.urls')),
    path('', include('django.contrib.auth.urls')),    
    path('users/', include('users.urls')),
    path('users/', include('django.contrib.auth.urls')),
]

settings.py

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAdminUser',
        'rest_framework.permissions.IsAuthenticated',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': [
       'rest_framework.authentication.SessionAuthentication',
       'rest_framework.authentication.TokenAuthentication', 
    ]
}

Solution

  • Readded authentication_classes = [TokenAuthentication]

    Tested using curl -H "Authorization: Token 144eaaf50a50f4055bc50878ee1b3593aa63d221" http://127.0.0.1:8000/api/users/ Now I see data in console as it should.