django-rest-framework authentication: require key parameter in URL?

前端 未结 1 1554
清酒与你
清酒与你 2021-01-14 08:56

I am working in Django 1.8 with the excellent django-rest-framework. I have a public RESTful API.

I would now like to start requiring a key GET paramet

相关标签:
1条回答
  • 2021-01-14 09:34

    Create a table which will contain all the keys that you issue to someone.

    Example:

    class RestApiKey(models.Model):
        api_key = models.CharField(max_length=100)
    

    Next create a custom Permision class which will check for the api Key in the url before forwarding the request to the view like:

    from rest_framework import permissions
    from yourappname.models import RestApiKey
    
    class OnlyAPIPermission(permissions.BasePermission):
        def has_permission(self, request, view):
            try:
                api_key = request.QUERY_PARAMS.get('apikey', False)
                RestApiKey.objects.get(api_key=api_key)
                return True
            except:
                return False
    

    So the request url has to be like http://yourdomain.com/?apikey=sgvwregwrgwg

    Next in your views add the permission class:

    class YourViewSet(generics.ListAPIView):
        permission_classes = (OnlyAPIPermission,)
    

    or if you are using function based views then do like:

    @permission_classes((OnlyAPIPermission, ))
    def example_view(request, format=None):
        . . .
    
    0 讨论(0)
提交回复
热议问题