Django Rest Framework IsAuthenticated permission Error Anonymous user

别说谁变了你拦得住时间么 提交于 2019-12-24 01:53:34

问题


I'm writing api using django rest framework using Token Authentication method written as below

@api_view(['GET'])
@permission_classes((IsAuthenticated, ))
def ah(request, format=None):
    result = request.user.is_authenticated()

    content = {"hello":result}
    return Response(content)

my settings are

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

    )
}

    MIDDLEWARE_CLASSES = [

    'django.contrib.sessions.middleware.SessionMiddleware',
    #'middleware.FirstTokenAuth.AuthenticationMiddlewareJWT',
    #'middleware.TokenAuthTest.JWTAuthenticationMiddleware',   
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.middleware.security.SecurityMiddleware',
    #'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    #'django.middleware.csrf.CsrfViewMiddleware',

    #'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',

]

When I call this API using IsAdminUserpermission class The django restframework returns:

403 response "detail": "Authentication credentials were not provided." if the token wasn't provided in the header

401 response "detail": "You do not have permission to perform this action." if the token was not for admin user

but the main problem is here when I set

@permission_classes((IsAuthenticated, ))

The API is called normally without returning 403 or 401 even if i didn't add a token to the header and the user returned is anonymous user. How can I prevent anonymous user from calling API and return 403 response for him.

Any help Please !!


回答1:


The @permission_classes is for identifying if the api needs authentication. If you want to use token, try to add @authentication_classes with TokenAuthentication inside. This will check the token in your header and create the user object inside request.




回答2:


Use this:

permission_classes = [permissions.IsAuthenticated,]

It worked for me.



来源:https://stackoverflow.com/questions/47677952/django-rest-framework-isauthenticated-permission-error-anonymous-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!