14

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).

Jason Goldstein
  • 1,117
  • 2
  • 11
  • 20

1 Answers1

19

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)
Community
  • 1
  • 1
Issac Kelly
  • 6,309
  • 6
  • 43
  • 50
  • Perfect. It's always the little things. Thanks. – Jason Goldstein Oct 18 '11 at 22:24
  • 1
    Your model resource should also allow for filtering on the field username. http://readthedocs.org/docs/django-tastypie/en/latest/resources.html#basic-filtering – iJK May 28 '12 at 18:53
  • Also make sure, that the shell is not interpreting the & of ..&api_key.. as backgrounding the command. Surrounding the URL with "" or escaping & with \& helped for me. – mab Sep 28 '12 at 18:37
  • 3
    where do I get the APIKey when sending the request to the server?? – megido Oct 15 '12 at 02:57
  • So instead of sending the password, I'll be sending an API key, which allows MITM attackers to do the same things as a password would allow them? – Dor Feb 05 '14 at 20:00
  • 1
    Two things @Dor. 1) Use SSL. 2) Presumably your API key has different access than your password. Potentially SSL + password access (BasicAuth) is good for many applications. Otherwise consider something like OAuth if third parties are writing applications. – Issac Kelly Feb 05 '14 at 23:32
  • In this question you will see how to get the ApiKey: http://stackoverflow.com/questions/25552577/tastypie-and-django-authorization-with-apikeyauthentication – Chesco Igual Sep 01 '14 at 13:14
  • Actually this: "curl http://localhost:8000/api/v1/books/?username=issackelly\&api_key=123456789adfljafal " did not work for me but when I removed the slash after "issackelly" the user "\" it started working. – Radek Dec 03 '16 at 21:12