Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
114 views
in Technique[技术] by (71.8m points)

python - Django rest framework - including an api key for access authorization

I'm creating a Restful API using Django Rest Framework, i'm not serving sensitive data but still i wanted to add some sort of authorization system for viewing my API endpoints.

Basically each user has an API key assigned, and in order to view any endpoint, the user needs to provide the key when performing any request. All the endpoints use only GET to retrieve the data, so what i did is the following:

  • The API key is provided in the GET params, so something like myURL/api/endpoint/?key=1234&filter=test
  • A middleware checks if that API key exists in my database, and if it does the user is able to get the data.

Here is my middleware:

TOKEN_QUERY = "key"

class TokenMiddleware(AuthenticationMiddleware):
    def process_request(self, request):

        if request.user.is_authenticated:
            return None
        else:     
            try:
                token = request.GET[TOKEN_QUERY]
            except Exception as e:
                # A token isn't included in the query params
                return JsonResponse({'error': 'Missing parameter: make sure to include your key.'})

            try:
                query = API_keys.objects.get(api_token=token)
            except:
                token = None

            if token != None:
                return None
            else:
                return JsonResponse({'error': 'Authentication failed. Make sure to provid a valid API key.'})

This system works without any problem, but i'm concerned about safety. How safe is this? Should i not use a GET request (of course i'll make sure to use HTTPS and SSL) ? Or is there a de facto way to create this kind of system? Any kind of advice is appreciated.

question from:https://stackoverflow.com/questions/66061505/django-rest-framework-including-an-api-key-for-access-authorization

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...