Tastypie APIKey authentication

前端 未结 1 1276
终归单人心
终归单人心 2020-12-25 07:57

How does the Tastypie APIKey authentication work? I know there is a signal as mentioned in the documentation:

from django.contrib.auth.models import User            


        
相关标签:
1条回答
  • 2020-12-25 08:29

    You can put this in models.py file of the relevant app (such as main/). What post_save.connect(create_api_key, sender=User) does is that everytime an User instance is saved, create_api_key() will be called.

    Now let's look into what create_api_key() does by diving a bit into the source of tastypie:

    class ApiKey(models.Model):
        user = models.OneToOneField(User, related_name='api_key')
        key = models.CharField(max_length=256, blank=True, default='')
        created = models.DateTimeField(default=datetime.datetime.now)
    
        def __unicode__(self):
            return u"%s for %s" % (self.key, self.user)
    
        def save(self, *args, **kwargs):
            if not self.key:
                self.key = self.generate_key()
    
            return super(ApiKey, self).save(*args, **kwargs)
    
        def generate_key(self):
            # Get a random UUID.
            new_uuid = uuid.uuid4()
            # Hmac that beast.
            return hmac.new(str(new_uuid), digestmod=sha1).hexdigest()
    
    
    def create_api_key(sender, **kwargs):
        """
        A signal for hooking up automatic ``ApiKey`` creation.
        """
        if kwargs.get('created') is True:
            ApiKey.objects.create(user=kwargs.get('instance'))
    

    As you can see, create_api_key() will create a new ApiKey record, which will be related to the calling User. This record will also have a HMAC key when it was saved to the ApiKey table. The key is generated by generate_key() function.

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