3

I dont really understand how this works but i want to add token authentication or a kinda API key authentication to my REST API clients. how do i go about this, like i want the API clients to have API key when connecting to the API, should this be on user based where each human user of the API has an API key,

Syd
  • 185
  • 1
  • 14
user3186887
  • 103
  • 2
  • 5
  • 1
    Have you try reading DRF [official docs](http://www.django-rest-framework.org/api-guide/authentication#tokenauthentication) on Token auth? – mariodev Jan 12 '14 at 10:26
  • For anybody wanting to access your API externally, the answer is yes. For anybody using your own software and accessing your data internally, then they don't need to have an API key. – Joe Jan 12 '14 at 12:38
  • See http://stackoverflow.com/questions/17560228/how-to-use-tokenauthentication-for-api-in-django-rest-framework – Kwaw Annor Sep 30 '14 at 14:27

1 Answers1

1

http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication states how to do this and as @kannor pointed out, see How to use TokenAuthentication for API in django-rest-framework

add to installed apps in settings.py

INSTALLED_APPS = (
     ...
    'rest_framework.authtoken'
)

Edit your models.py and add the following below to add a "hook"/"event" for the on save of your users

from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        Token.objects.create(user=instance)

and add the following to your urls.py

from rest_framework.authtoken import views
urlpatterns += [
    url(r'^api-token-auth/', views.obtain_auth_token)
]
Community
  • 1
  • 1
PvdL
  • 1,578
  • 1
  • 20
  • 33