Amistad
Amistad

Reputation: 7410

Authentication in Django rest framework function based views

So i have a function based view in my Django rest framework and i do authentication in it as follows:

from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view(['GET'])
def analytics_filter_values(request):
    if request.user.is_authenticated():
        pass
    else:
        return Response("Unauthorized access", status=status.HTTP_403_FORBIDDEN)
.....
<business logic>
.....
.....

Now in this view file,I have quite a few views and inside each function,i use the if else to check the authentication.So in order to reduce the lines of code,i decided to make this a function and then call it inside each function view as follows :

from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response

def check_authentication(request):
if request.user.is_authenticated():
    pass
else:
    return Response("Unauthorized access", status=status.HTTP_403_FORBIDDEN)

@api_view(['GET'])
def analytics_filter_values(request):
    check_authentication(request)
.....
<business logic>
.....
.....

However,this does not work.This could be really silly but i am clueless as to what is amiss here..

Upvotes: 11

Views: 5329

Answers (1)

Anush Devendra
Anush Devendra

Reputation: 5475

You have to use django restframework @permission_classes decorator to check if user is authenticated or not.

You can do like:

from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import permission_classes

@api_view(['GET'])
@permission_classes((IsAuthenticated, ))
def example_view(request, format=None):
    .....
    <business logic>
    .....

Here @permission_classes((IsAuthenticated, )) decorator will check if the user is authenticated before forwarding the request to your view.

You can learn more here

Upvotes: 25

Related Questions