Ahmad Haidar
Ahmad Haidar

Reputation: 61

Django rest framework Anonymous user is always Authenticated

I'm trying to authenticate my web API method using django rest framework isauthenticated permission and TokenAuthentication The API method:

@api_view(['Post'])
@permission_classes((IsAuthenticated,))
def listofgroups(request):
    try:
        logout(request)
        data = request.data
        page_size = data.get('pagesize')
        page_number = data.get('pagenumber')
        group_qs = Group.objects.all()
        paginator = Paginator(group_qs, int(page_size))
        group_list = paginator.page(int(page_number))
        #group_list = tools.paginate_query_set(group_qs, 1, 3)
        #list  = group_list[0]['model']
        groups = [get_group_dto(g) for g in group_list]
        sorted_groups = sorted(groups, key=lambda k: k['user_count'], reverse = True)
        group_list_dto = {
        "grps": sorted_groups, 
        "success":1,
        "fail":0
        }
        return Response(group_list_dto)
    except Exception as e:
        #.error("Error %s"(e), exc_info = 1) 
        return Response({"success" : 0, "error": str(e)})

Basically i should always set Authorization in the header like :

"Authorization":"Token a26171d30745cc94bcd6ac42d9bc94e1d3992948"

this token is based on rest_framework.authtoken

The Error is that I can get the data with response 200 without even setting the Token in the header because its returning anonymous user which is authenticated from the back end in django.

How can I prevent anonymous users from being authenticated and return 403 response error for them using django rest framework

I appreciate any help

Upvotes: 1

Views: 4031

Answers (2)

Kenedy Nopriansyah
Kenedy Nopriansyah

Reputation: 741

you can this do,

to stay safe and always ask the user for a token, and you don't need to call permission_classes, it will automatically be isAuthenticated

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

Upvotes: 0

Compro Prasad
Compro Prasad

Reputation: 162

There are actually many classes defined in django rest framework for validation purposes. What I guess in your case is that you will need the following set of decorators:

@api_view(['POST'])
@authentication_classes((TokenAuthentication,))
@permission_classes((IsAuthenticated,))

Considering you have set the header properly it wont be a problem with the above code.

Upvotes: 1

Related Questions