我有带 api key 身份验证的 tastypie api。
对于 GET 请求,它可以双向工作,但对于 post 请求,它不起作用。
url = http://localhost:8000/api/path/?api_key=key&username=username
在 View 中,当我尝试打印 request.user 时,当请求来自 postman 时,它是普通/真实用户。但是对于 python 请求,它是匿名用户。
对于 python 请求,我正在这样做:
url = http://localhost:8000/api/path/?api_key=key&username=username
d = {"some": "data"}
r = requests.post(url, data=json.dumps(d), headers={"content-type": "application/json"})
postman 提供的代码:
POST /api/v1/abc/?api_key=somekey&username=something HTTP/1.1
Host: localhost:8000
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: something
{"something":"something"}
如有任何问题,请告诉我。
我的 api 身份验证无法正常工作的资源:
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
fields = ['username', 'email', 'first_name', 'last_name']
resource_name = 'user'
authentication = ApiKeyAuthentication()
请您参考如下方法:
确保您没有使用 SessionAuthentication 或在您的身份验证中启用 enforce_csrf。由于 postman 也会随请求发送浏览器 cookie,这可能是您获得不同行为的原因。
如果是这样,则表示 API 身份验证不起作用。由于 postman 正在使用 SessionAuthentication,因此它可以工作。确保您已在 INSTALLED_APPS 中添加了 tastypie 并在数据库中创建/存储了 api key 。
