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,

3
  • 1
    Have you try reading DRF official docs on Token auth? Commented Jan 12, 2014 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. Commented Jan 12, 2014 at 12:38
  • See stackoverflow.com/questions/17560228/… Commented Sep 30, 2014 at 14:27

1 Answer 1

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)
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.