[Answered ]-Django rest framework โ€“ including an api key for access authorization

1๐Ÿ‘

You can try this

from rest_framework import permissions

TOKEN_QUERY = "key"

# guest token validation class    
class GuestTokenPermission(permissions.BasePermission):

    def __init__(self, allowed_methods):
        self.allowed_methods = allowed_methods

    def has_permission(self, request, view):

        token = request.META.get('HTTP_GUEST_TOKEN', None)

        if token == TOKEN_QUERY:

            return request.method in self.allowed_methods

        else:

            if request.user.is_superuser:

                return request.method in self.allowed_methods
 
  # put where you want to set permission
 permission_classes = (partial(GuestTokenPermission, ['GET', 'POST', 'HEAD']),)

Refer https://www.django-rest-framework.org/api-guide/permissions/

๐Ÿ‘คrahul.m

Leave a comment