IsAuthenticated权限错误匿名用户

IsAuthenticated权限错误匿名用户

本文介绍了Django Rest Framework IsAuthenticated权限错误匿名用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用django rest框架编写api,并使用如下编写的令牌身份验证方法

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)

我的设置是

    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',

]

当我使用IsAdminUserpermission类调用此API时,django restframework返回:

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

401响应详细信息":您无权执行此操作." 如果令牌不是管理员用户

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

即使我没有在标头中添加令牌并且返回的用户是匿名用户,该API也会正常调用而不会返回403或401.如何防止匿名用户调用API并为他返回403响应.

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.

任何帮助,请!!

推荐答案

使用此:

permission_classes = [permissions.IsAuthenticated,]

对我有用.

这篇关于Django Rest Framework IsAuthenticated权限错误匿名用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 08:31