What is the right way to write a django-piston client?

前端 未结 1 860
轻奢々
轻奢々 2021-02-01 10:31

I\'ve been reading a lot on django-piston and using to to make an API for an app I\'m development, but I\'m getting hung up on the client side of the world. I\'ve written the ha

相关标签:
1条回答
  • 2021-02-01 11:12

    You can write your own authentication module. Here's an example:

    class ApiKeyAuthentication(object):
    
        def is_authenticated(self, request):
            auth_string = request.META.get("HTTP_AUTHORIZATION")
    
            if not auth_string:
                return False
    
            key = get_object_or_None(ApiKey, key=auth_string)
    
            if not key:
                request.user = AnonymousUser()
                return False
    
            request.user = key.user
    
            return True
    
        def challenge(self):
            resp = HttpResponse("Authorization Required")
            resp['WWW-Authenticate'] = "Key Based Authentication"
            resp.status_code = 401
            return resp
    

    You'll need a model to store a mapping of API keys to Users:

    class ApiKey(models.Model):
        user = models.ForeignKey(User, related_name='keys')
        key = models.CharField(max_length=KEY_SIZE)
    

    You'll need some method to generate the actual keys. Something like this will work (say, in the ApiKey model's save method:

    key = User.objects.make_random_password(length=KEY_SIZE)
    
    while ApiKey.objects.filter(key__exact=key).count():
        key = User.objects.make_random_password(length=KEY_SIZE)
    

    Lastly, hook up your new authentication backend:

    # urls.py
    
    key_auth = ApiKeyAuthentication()
    
    def ProtectedResource(handler):
        return resource.Resource(handler=handler, authentication=key_auth)
    
    your_handler = ProtectedResource(YourHandler)
    

    As for swapping username / password for an API key, just write a handler that uses BasicAuthentication to create and return new ApiKey (for request.user).

    0 讨论(0)
提交回复
热议问题