FOR DEVELOPERS

Django Rest Framework Authentication: A Beginner’s Guide

Django REST Framework Authentication

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

  • The various authentication options that are available in DRF.
  • How each method works and how to implement them. My goal is to demystify authentication and provide a starting point for securing your APIs.
  • The basic and token authentication, sessions, JWTs, OAuth, and custom authentication.
  • Pros and cons of each approach so you can pick the right one for your project needs.
  • Examples of code snippets to explain concepts step-by-step.

By the end, you will have the authority to build your secure APIs using the robust authentication tools provided by DRF.

Introduction to API authentication

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:

  • Security - Prevent unauthorized access to APIs that contain sensitive data or can perform critical actions.
  • Personalization - Identify individual users to provide customized responses and experiences.
  • Analytics - Track API usage on a per-user basis for analytics and billing.
  • Rate limiting - Limit requests on a per-user basis to prevent abuse.

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 authentication

Django REST Framework provides the following built-in authentication classes:

  • BasicAuthentication
  • TokenAuthentication
  • SessionAuthentication
  • JSONWebTokenAuthentication

Additionally, you can also write your custom authentication classes. Let's look at how each type works.

Basic authentication

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.py
REST_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-simplejwt

Then add it to your installed apps:

# settings.py

INSTALLED_APPS = [ # ... 'rest_framework_simplejwt', ]

In your REST framework settings, include the TokenAuthentication class:

# settings.py

REST_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.py

from rest_framework_simplejwt.views import( TokenObtainPairView, TokenRefreshView, )

urlpatterns = [ # ...

path(&#39;api/token/&#39;, TokenObtainPairView.as_view(), name=&#39;token_obtain_pair&#39;),

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.py
INSTALLED_APPS = [
    #...
    &#39;django.contrib.sessions&#39;
]

MIDDLEWARE = [
    # ...
    &#39;django.contrib.sessions.middleware.SessionMiddleware&#39;,
    # ...
]

REST_FRAMEWORK = {
    &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: [
        &#39;rest_framework.authentication.SessionAuthentication&#39;,
        # ...
    ]
}         </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(&quot;User logged in&quot;)

class LogoutView(APIView): def post(self, request): # Logout user

    return Response(&quot;User logged out&quot;)</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 - jwt

In "settings.py", add the JWT authentication class:

  # settings.py

REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', # ... ] }

You'll also need to add views for obtaining and refreshing JWTs:

   # urls.py

from rest_framework_jwt.views import (

obtain_jwt_token, Refresh_jwt_token, )

urlpatterns = [
    # ...
   
    path(&#39;api/token/&#39;, obtain_jwt_token),
    path(&#39;api/token/refresh/&#39;, 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 &lt; token &gt;</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:

  • django-oauth-toolkit - Provides OAuth 2.0 server capabilities.
  • django-rest-framework-social-oauth2 - OAuth client package for social authentication.

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.py
INSTALLED_APPS = [
    # ...
    &#39;rest_framework_social_oauth2&#39;,
]

Include the OAuth2 authentication class:

    # settings.py

REST_FRAMEWORK = {
    # ...
    &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: [
        &#39;rest_framework_social_oauth2.authentication.OAuth2Authentication&#39;,
    ]
}</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 = &#39;&#39;  # Client ID
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = &#39;&#39;  # Client Secret</pre><p>Finally, trigger the social auth login process by redirecting users to the backend&#39;s authorization URL:</p><pre>    from rest_framework_social_oauth2.views import
    (
        OAuth2LoginView,
    )


# urls.py


path(
    &#39;api/auth/login/google-oauth2/&#39;,
    OAuth2LoginView.as_view(provider=&#39;google-oauth2&#39;),]
)</pre><p>This will redirect to Google&#39;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.py
from 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=&quot;API&quot;
       
    ...</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 = {
    &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: [
        &#39;path.to.CustomAuth&#39;,
        ...
    ]
}</pre><p>This allows you to craft authentication that fits the specific needs of your API.</p><p>We&#39;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.

Author

  • Django Rest Framework Authentication: A Beginner’s Guide

    Steve Yonkeu

    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.

Frequently Asked Questions

Django REST Framework Authentication refers to the methods and mechanisms used to verify the identity of users accessing a web API built with Django REST Framework. It ensures that only authorized users can interact with the API.

Session Authentication leverages Django's session framework and is suitable for web APIs that need to maintain user state. It stores session data server-side.

Rate-limiting can be implemented on a per-user basis to prevent abuse. DRF allows you to configure rate-limiting rules based on your API's needs.

API Authentication is crucial to prevent unauthorized access to sensitive data and functionalities. It helps maintain security, personalization, analytics, and rate limiting for APIs.

DRF supports OAuth 2.0 integration through packages like django-oauth-toolkit. This allows users to log in via external OAuth providers like Google or Facebook.

Yes, you can implement multiple authentication classes in DRF, creating a layered approach to authentication for added security.

Token Authentication uses randomly generated tokens instead of usernames and passwords. These tokens are associated with user profiles and can be used for secure API access without exposing credentials.

Custom Authentication in DRF allows you to create authentication methods tailored to your specific project requirements. You can implement custom validation logic and integrate external systems.

To maintain API security, stay updated with the latest security best practices, regularly review and update your authentication mechanisms, and follow a defense-in-depth approach.

View more FAQs
Press

Press

What’s up with Turing? Get the latest news about us here.
Blog

Blog

Know more about remote work. Checkout our blog here.
Contact

Contact

Have any questions? We’d love to hear from you.

Hire remote developers

Tell us the skills you need and we'll find the best developer for you in days, not weeks.