Leverage Turing Intelligence capabilities to integrate AI into your operations, enhance automation, and optimize cloud migration for scalable impact.
Advance foundation model research and improve LLM reasoning, coding, and multimodal capabilities with Turing AGI Advancement.
Access a global network of elite AI professionals through Turing Jobs—vetted experts ready to accelerate your AI initiatives.
Building a web API can be daunting for beginners. You might be wondering: how to handle all the CRUD logic on the backend. How to secure your API endpoints? Django REST Framework (DRF) can help you. DRF simplifies building APIs in Django by providing a powerful set of tools to speed up development.
One of the most important aspects of any web API is authentication. You need to control who can access the backend resources and data. DRF has built-in solutions to make handling authentication easy.
In this beginner’s guide, we will walk you through
By the end, you will have the authority to build your secure APIs using the robust authentication tools provided by DRF.
Imagine you want to use an app to order some pizza. That app needs to communicate with the restaurant’s systems to place the order. That's where APIs come in!
The app connects to the API and says "Hey! I'd like to order a large pepperoni pizza for my friend." The API takes the order request and informs that an order has been placed. Without APIs, those apps wouldn't be able to interact with all the businesses we know and love.
But APIs aren't just for takeout orders! All kinds of companies use them: social networks, banks, online stores, etc. APIs allow different systems to share data and functionality in a standardized way.
Now here's an important question, if APIs allow access to all that precious data and functionality, how do we stop just anyone from strolling in? That's where authentication comes in.
Authentication is like the bouncer at an exclusive club. It checks who can be allowed entry and needs to be kept away. For APIs, authentication verifies the identity of the user trying to connect. This allows the API to determine if the user is authorized to take certain actions. For example, users of our pizza app should only be able to access their orders and not anyone else's!
Authentication keeps that data safe and secure. There are different ways by which APIs can authenticate users, like using unique tokens or login credentials. As we dive deeper into APIs, we'll make sure to guide you through the various authentication options.
Some key reasons you need API authentication include:
Django REST Framework supports multiple authentication schemes that make it easy to get your API properly secured. Let's go through each option.
Django REST Framework provides the following built-in authentication classes:
Additionally, you can also write your custom authentication classes. Let's look at how each type works.
This uses standard HTTP Basic Authentication. The username and password are passed in the Authorization header when making requests. For example:
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
To use basic authentication, add BasicAuthentication to the DEFAULT_AUTHENTICATION_CLASSES list in your DRF settings:
# settings.pyREST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', # ... ] }</pre><p>Basic authentication is suitable for quick prototyping and tests. However, you should avoid using it in production since the credentials are passed in plain text.</p>
Token authentication
This uses an arbitrary token, which is used instead of a username and password to authenticate users. Typically these tokens are randomly generated strings that are stored with the user profile.
To get started, install the django-rest-framework-simplejwt package:
$ pip install djangorestframework-simplejwtThen add it to your installed apps:
# settings.pyINSTALLED_APPS = [ # ... 'rest_framework_simplejwt', ]
In your REST framework settings, include the TokenAuthentication class:
# settings.pyREST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', # ... ] }In your REST framework settings, include the TokenAuthentication class:
You will also need to create views for obtaining tokens and refreshing them when they expire. The JWT package provides these for you.
Add the JWT views to your "urls.py":
# urls.pyfrom rest_framework_simplejwt.views import( TokenObtainPairView, TokenRefreshView, )
urlpatterns = [ # ...
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ]
Now users can obtain a token by posting their username and password to the token_obtain_pair endpoint. This will return an access and refresh token.
The refresh token can be used to get new access tokens when they expire. This allows users to remain authenticated indefinitely.
To authenticate requests, include the access token in the Authorization header:
Authorization: Bearer <token>Token authentication is useful for production APIs. It avoids sending credentials with each request. The tokens can also be revoked individually on the server side.
Session authentication
This leverages Django's session framework to authenticate users. Users are logged in and session data is stored server-side linked to that user.
Enable sessions in Django and make sure SessionAuthentication is in the authentication classes:
#settings.pyINSTALLED_APPS = [ #... 'django.contrib.sessions' ] MIDDLEWARE = [ # ... 'django.contrib.sessions.middleware.SessionMiddleware', # ... ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', # ... ] } </pre><p>Add login and logout views to allow obtaining and destroying session,m keys:</p><pre># views.py
from rest_framework.response import Response from rest_framework.views import APIView
class LoginView(APIView): def post(self, request): username = request.data.get('username') password = request.data.get('password')
# Validate credentials # Login user return Response("User logged in")
class LogoutView(APIView): def post(self, request): # Logout user
return Response("User logged out")</pre><p>Users can now log in via the login view to obtain a session ID. This session ID should be included in a cookie for subsequent authenticated requests.</p><p>Session auth is good for web APIs that need to maintain user state. However, it requires storing session data server-side so it may not scale as well as token auth.</p>
JSON web token authentication
JSON Web Token (JWT) is an open standard that defines a compact way to securely transmit information between parties. Django REST framework provides a package for authenticating with JWTs.
First install the djangorestframework-jwt package:
pip install djangorestframework - jwtIn "settings.py", add the JWT authentication class:
# settings.pyREST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', # ... ] }
You'll also need to add views for obtaining and refreshing JWTs:
# urls.pyfrom rest_framework_jwt.views import (
obtain_jwt_token, Refresh_jwt_token, )
urlpatterns = [ # ... path('api/token/', obtain_jwt_token), path('api/token/refresh/', refresh_jwt_token), ]</pre><p>To get a JWT, post a username and password to the obtain_jwt_token endpoint. This will return a signed token that can be used in the Authorization header:</p><pre> Authorization: JWT < token ></pre><p>When the short-lived access tokens expire, use the refresh_jwt_token view to obtain a new access token.</p><p>JWTs are a great stateless authentication mechanism for APIs. They contain all the user information encrypted in the token so that no database lookups are needed.</p>
OAuth 2.0 authentication
For more robust authentication, Django REST Framework provides integration with OAuth 2.0. OAuth is an authorization standard that allows users to grant third-party access to their data.
Typically, this allows users to log in via an external OAuth provider like Google or Facebook. DRF makes the OAuth 2.0 implementation easier.
There are a few packages for integrating OAuth 2.0:
For this example, we'll use django-rest-framework-social-oauth2 to add a social login.
Install the package:
pip install djangorestframework - social - oauth2
Add it to INSTALLED_APPS:
# settings.pyINSTALLED_APPS = [ # ... 'rest_framework_social_oauth2', ]
Include the OAuth2 authentication class:
# settings.pyREST_FRAMEWORK = { # ... 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_social_oauth2.authentication.OAuth2Authentication', ] }</pre><p>Configure the OAuth providers you want to support, like Google and Facebook. This involves registering your app with each provider.</p><p>For example, for Google OAuth:</p><pre> # settings.py SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '' # Client ID SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '' # Client Secret</pre><p>Finally, trigger the social auth login process by redirecting users to the backend's authorization URL:</p><pre> from rest_framework_social_oauth2.views import ( OAuth2LoginView, ) # urls.py path( 'api/auth/login/google-oauth2/', OAuth2LoginView.as_view(provider='google-oauth2'),] )</pre><p>This will redirect to Google's OAuth consent page. Once authorized, the user is redirected back and authenticated.</p><p>OAuth is great for securely delegating authentication to trusted external providers like Google and Facebook. This prevents you from having to store usernames and passwords yourself.</p>
Custom authentication
If the built-in authentication doesn't meet your needs, you can create your custom authentication classes by subclassing BaseAuthentication.
For example:
# custom_auth.pyfrom rest_framework.authentication import BaseAuthentication class CustomAuth(BaseAuthentication): def authenticate(self, request): # Check credentials and return (user, token) return None def authenticate_header(self, request): # Return custom auth header, e.g. # WWW-Authenticate: Custom realm="API" ...</pre><p>The authenticate method should check the incoming credentials and return a user-token tuple if valid. Otherwise, return None.</p><p>You can tie into external authentication systems and implement custom validation logic here.</p><p>Some examples of custom authentication:</p><ul><li>HTTP custom headers</li><li>External OAuth provider</li><li>IP whitelisting</li><li>Device ID checking</li></ul><p>To install the custom authentication class, add it to the <a href="https://www.turing.com/kb/restful-api-using-flask-framework" target="_self" >REST framework</a> settings:</p><pre> # settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'path.to.CustomAuth', ... ] }</pre><p>This allows you to craft authentication that fits the specific needs of your API.</p><p>We've covered the various built-in authentication options provided by Django REST Framework that you can use to secure your APIs.</p><p>Some key points to consider when implementing API authentication:</p><ul><li>Use HTTPS to encrypt all authentication credentials and traffic.</li><li>Access tokens should be short-lived and support rotation.</li><li>Restrict permissions based on authentication to limit data exposure.</li><li>Adopt a stateless authentication pattern like JWTs for scalability.</li><li>Offload authentication to trusted external providers like OAuth when possible.</li><li>Log and monitor authentication failures to detect attacks.</li><li>Practice defense in depth with multiple authentication layers if needed.</li></ul><p>With proper authentication, you can build secure APIs that provide authorized access to backend resources and data. The techniques discussed here should provide a good starting point for implementing API authentication using the Django REST Framework.</p>
Conclusion
Django REST Framework Authentication is a crucial component in building secure and reliable web APIs. This beginner's guide introduced you to various authentication options within DRF, including Basic Authentication, Token Authentication, Session Authentication, JSON Web Token Authentication, OAuth 2.0 Authentication, and Custom Authentication.
Understanding these authentication methods empowers you to make informed decisions about securing your APIs. Whether you're a novice or have little experience with APIs, you now know how to implement robust authentication mechanisms tailored to your project's needs.
To keep your information secure, always prioritize the protection of sensitive data and resources, use HTTPS for encryption, and consider short-lived access tokens with rotation for enhanced security. By following best practices and leveraging the tools provided by Django REST Framework, you can confidently build secure APIs that meet your project's requirements. Building secure APIs is a journey, and with the right authentication in place, you're well on your way to success.
Steve Yonkeu is a software engineer with some diverse experience in DevOps, architecture, and blockchain. Has been leading developer's teams in providing the best solution to problems with low resource utilization.