Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 854
Amistad Avatar asked Nov 16 '15 08:11

Amistad


People also ask

What is the best authentication for Django REST framework?

And these are all provided by drf(django rest framework) and other than these like oauth, oauth2 based authentication are provided by the efforts of the community with help of other python packages. And they can be easily used in the production environment.

How do you implement basic authentication in Django REST framework?

Here we set the BasicAuthentication scheme globally, so we don't need to set it for each view. But we need to set the permission class since, by default, the permission class is set to AllowAny, which allows unrestricted access. To make use IsAuthenticated class we need to import it from rest_framework. permissions.


1 Answers

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

like image 53
Anush Devendra Avatar answered Oct 19 '22 07:10

Anush Devendra