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,
-
1Have you try reading DRF official docs on Token auth?mariodev– mariodev2014-01-12 10:26:46 +00:00Commented 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.Joe– Joe2014-01-12 12:38:40 +00:00Commented Jan 12, 2014 at 12:38
-
See stackoverflow.com/questions/17560228/…Kwaw Annor– Kwaw Annor2014-09-30 14:27:38 +00:00Commented Sep 30, 2014 at 14:27
Add a comment
|
1 Answer
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)
]