Reputation: 103
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,
Upvotes: 3
Views: 2864
Reputation: 1593
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)
]
Upvotes: 1