小编典典

Django Tastypie:如何使用API​​密钥进行身份验证

django

我正在用TastyPie制作内部API。我有

from tastypie.authentication import ApiKeyAuthentication
class MyResource(ModelResource):
  Meta:
    authentication = ApiKeyAuthentication()

禁用身份验证规则后,我的API效果很好。启用它后,无论尝试如何,都会收到401(未经授权)的响应。

我敢肯定,一旦你看到它的实际作用,这就是其中的一件事,但与此同时,请告知如何提出请求(GET)。


阅读 411

收藏
2020-04-01

共1个答案

小编典典

将用户名和api_key参数添加到你的GET变量中。确保你拥有

curl http://localhost:8000/api/v1/books/?username=issackelly\&api_key=123456789adfljafal

设置时,请确保遵循docs的其他说明:

ApiKey身份验证
作为要求敏感数据(例如密码)的一种替代方法,ApiKeyAuthentication允许你仅收集用户名和计算机生成的api密钥。Tastypie专门为此目的提供了特殊的模型,因此你需要确保自己在INSTALLED_APPS中。

Tastypie包含一个信号功能,可用于自动创建ApiKey对象。连接起来看起来像:

from django.contrib.auth.models import User
from django.db import models
from tastypie.models import create_api_key

models.signals.post_save.connect(create_api_key, sender=User)
2020-04-01