Token Auth
Token Auth
For an implementation which allows more than one token per user, has some
tighter security implementation details, and supports token expiry, please see
the Django REST Knox third party package.
INSTALLED_APPS = [
...
'rest_framework.authtoken'
print(token.key)
If you want to use a different keyword in the header, such as Bearer , simply
subclass TokenAuthentication and set the keyword class variable.
Unauthenticated responses that are denied permission will result in an HTTP 401
Unauthorized response with an appropriate WWW-Authenticate header. For
example:
WWW-Authenticate: Token
The curl command line tool may be useful for testing token authenticated
APIs. For example:
Note: If you use TokenAuthentication in production you must ensure that your
API is only available over https .
Generating Tokens
By using signals
If you want every user to have an automatically generated Token, you can simply
catch the User's post_save signal.
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
if created:
Token.objects.create(user=instance)
Note that you'll want to ensure you place this code snippet in an
installed models.py module, or some other location that will be imported by
Django on startup.
If you've already created some users, you can generate tokens for all existing
users like this:
Token.objects.get_or_create(user=user)
urlpatterns += [
path('api-token-auth/', views.obtain_auth_token)
Note that the URL part of the pattern can be whatever you want to use.
{ 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }
Note that the default obtain_auth_token view explicitly uses JSON requests and
responses, rather than using default renderer and parser classes in your
settings.
class CustomAuthToken(ObtainAuthToken):
serializer = self.serializer_class(data=request.data,
context={'request': request})
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
return Response({
'token': token.key,
'user_id': user.pk,
'email': user.email
})
urlpatterns += [
path('api-token-auth/', CustomAuthToken.as_view())
your_app/admin.py :
TokenAdmin.raw_id_fields = ['user']
this command will return the API token for the given user, creating it if it doesn't
exist:
In case you want to regenerate the token (for example if it has been
compromised or leaked) you can pass an additional parameter:
Unauthenticated responses that are denied permission will result in an HTTP 403
Forbidden response.
Warning: Always use Django's standard login view when creating login pages.
This will ensure your login views are properly protected.
RemoteUserAuthentication
This authentication scheme allows you to delegate authentication to your web
server, which sets the REMOTE_USER environment variable.
Custom authentication
To implement a custom authentication scheme,
subclass BaseAuthentication and override the .authenticate(self,
request) method. The method should return a two-tuple of (user, auth) if
authentication succeeds, or None otherwise.
Example
The following example will authenticate any incoming request as the user given
by the username in a custom request header named 'X-USERNAME'.
class ExampleAuthentication(authentication.BaseAuthentication):
username = request.META.get('HTTP_X_USERNAME')
if not username:
return None
try:
user = User.objects.get(username=username)
except User.DoesNotExist: