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..
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With