2
votes

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 !!

2
the issue is with Authentication not with permission, authentication backend is setting it as authenticated . have you added 'rest_framework.authtoken' to INSTALLED_APPS .. are you creating the tokens ? - Saji Xavier
Hi @SajiXavier yes i added restframework.authtoken to installed apps and created tokens and are saved in the database - Ahmad Haidar

2 Answers

0
votes

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.

0
votes

Use this:

permission_classes = [permissions.IsAuthenticated,]

It worked for me.