Django Rest Framework IsAuthenticated () Method Does Not Work for AnonymousUser

I have a ListView and IsAuthenticated permission is set for it. When I click on the URL in an incognito window, I can view the data without user logging in.

Here is my serializer

class BlogListSerializer(ModelSerializer): url = HyperlinkedIdentityField( view_name="blog_api:post_detail", lookup_field="slug" ) class Meta: model = Blog fields = [ 'url', 'title', 'category', 'date', 'publish', 'draft' ] 

Below is my opinion

 from rest_framework.permissions import IsAuthenticated class BlogListAPIView(ListAPIView): queryset = Blog.objects.filter(publish=True, draft=False) serializer_class = BlogListSerializer permission_classes = [IsAuthenticated] 

Settings files

 REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ) } 

Middleware Settings

 MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] 

So what happens when I try to access a user by calling get_object on BlogListAPIView, it throws an error that is not JSON serializable. For some reason, middleware accepts AnonymousUser as a user. If AnonymousUser is logged in, it must obtain IsAuthenticated permission. This is basically what should happen. Why does AnonymousUser gain access and IsAuthenticated () not working?

+8
django django-views django-rest-framework django-serializer
source share
2 answers

The problem disappeared by upgrading from Django 1.9 to Django 1.10 and using DRF 3.3.7.

+2
source share

Of course, there are other problems that are not in your question. I created a new project with the fragments you provided and will receive http 401 when I get to the URL without logging in. I provided the codes on Github:

get https://github.com/Rmaan/pastebin/tree/so-47596482

start the server and go to http: // localhost: 8000 / blog

+5
source share

All Articles