Django Tastypie: How to Authenticate with API Key

妖精的绣舞 提交于 2019-11-26 18:16:37

问题


I'm making an internal API with TastyPie. I have

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

With Auth rules disabled, my API works great. With it on, I get a 401 (UNAUTHORIZED) response no matter what I try.

I'm sure this is one of those things that's really obvious once you've see it in action, but in the meantime, please advise how to to make the request (a GET).


回答1:


Add the username and api_key parameters to your GET variables. Make sure that you have the

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

Make sure to follow the other instructions from teh docs when setting it up:

ApiKeyAuthentication

As an alternative to requiring sensitive data like a password, the ApiKeyAuthentication allows you to collect just username & a machine-generated api key. Tastypie ships with a special Model just for this purpose, so you'll need to ensure tastypie is in INSTALLED_APPS.

Tastypie includes a signal function you can use to auto-create ApiKey objects. Hooking it up looks like:

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)


来源:https://stackoverflow.com/questions/7814128/django-tastypie-how-to-authenticate-with-api-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!