Reputation: 385
I have a ListView and it has permission set to IsAuthenticated, when I hit the URL in an incognito window, I'm able to view the data without having the user logged 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 view
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's happening is, when I try to access the user by calling get_object on BlogListAPIView, it throws an error is not JSON serializable. For some reason, middleware is taking AnonymousUser as a User. If there is AnonymousUser logged in it should fail IsAuthenticated permission. This is what basically should happen Why AnonymousUser is getting accessed and IsAuthenticated() failing?
Upvotes: 8
Views: 3517
Reputation: 12087
The issue was gone by upgrading from Django 1.9 to Django 1.10 and using DRF 3.3.7.
Upvotes: 2
Reputation: 6536
There is certainly some other problems that is not listed in your question. I created a fresh project with snippets you provided and will get http 401 when I hit the URL without logging in. I provided codes in Github:
get https://github.com/Rmaan/pastebin/tree/so-47596482
runserver and browse to http://localhost:8000/blog
Upvotes: 5