Token-based Authentication in Django
Token-based authentication is a common method of securing APIs in Django applications. It allows users to authenticate with the server by passing a token in the request header, rather than requiring the user to send their username and password with every request. Django Rest Framework (DRF) provides built-in support for token authentication. In this article, we will walk through how to set up token-based authentication in Django using DRF.
1. What is Token-based Authentication?
Token-based authentication is an authentication scheme that involves issuing a token when a user logs in successfully. The user then includes this token in the header of subsequent HTTP requests to authenticate themselves. The server verifies the token to ensure the request is from an authenticated user.
Tokens are typically issued in the form of a string that can be validated and decoded. They are stateless, meaning the server does not need to store any session data about the user. This makes token-based authentication ideal for stateless APIs, especially in RESTful services.
2. Installing Django Rest Framework and DRF Token Authentication
To set up token-based authentication, you need to install Django Rest Framework and the DRF token authentication package. You can install them using the following command:
pip install djangorestframework
pip install djangorestframework-simplejwt
Once you’ve installed the necessary packages, add them to the INSTALLED_APPS
section in your settings.py
file:
# settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework', # DRF
'rest_framework.authtoken', # Token authentication
]
3. Setting Up Token Authentication
Now, let's configure Django Rest Framework to use token-based authentication. Open your settings.py
file and configure the default authentication classes to include token authentication.
# settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
}
With this configuration, DRF will now use token authentication by default for all API views that require authentication.
4. Creating the Token Authentication Views
To authenticate using tokens, the user first needs to obtain a token. DRF provides a built-in view to obtain tokens, which can be used to authenticate subsequent requests. To enable token generation, include the following URLs in your urls.py
file:
# urls.py
from django.urls import path
from rest_framework.authtoken.views import obtain_auth_token
urlpatterns = [
path('api/token/', obtain_auth_token, name='api_token'),
]
The obtain_auth_token
view will accept a POST request containing the user’s username and password and return a token that can be used for authentication in subsequent requests. Here’s an example of how to make a request to this view.
Example: Requesting a Token
To obtain a token, send a POST request to /api/token/
with the user’s username
and password
in the request body. You can do this using curl
, Postman, or any HTTP client:
curl -X POST -d "username=myuser&password=mypassword" http://127.0.0.1:8000/api/token/
If the username and password are correct, the response will include a token, which looks something like this:
{
"token": "abc123xyz456def789"
}
5. Using the Token for Authentication
Once you have the token, you can include it in the headers of subsequent requests to authenticate the user. The token should be passed in the Authorization
header as follows:
Authorization: Token abc123xyz456def789
Example: Accessing a Protected API View
Let’s say you have a protected API view that returns user details. You can protect this view with token authentication. Here's an example view that requires token authentication:
# views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
class UserDetailView(APIView):
permission_classes = [IsAuthenticated] # Only authenticated users can access this view
def get(self, request):
content = {'message': 'Hello, {}'.format(request.user.username)}
return Response(content)
This view requires the user to be authenticated. If the user provides the correct token, they will be able to access this view. You can define a URL for this view as follows:
# urls.py
from django.urls import path
from .views import UserDetailView
urlpatterns = [
path('api/user/', UserDetailView.as_view(), name='user-detail'),
]
To access this view, the user must include the token in the Authorization
header:
curl -H "Authorization: Token abc123xyz456def789" http://127.0.0.1:8000/api/user/
If the token is valid, the response will contain the message with the authenticated user's username:
{
"message": "Hello, myuser"
}
6. Conclusion
In this article, we covered how to set up token-based authentication in Django using Django Rest Framework. Token authentication is a powerful and flexible method for securing your API endpoints, allowing users to authenticate with a single token rather than sending their credentials with every request. By using DRF's built-in tools, we can easily implement token authentication and protect our API views with minimal configuration.