Authentication

Authentication in Django Rest Framework (DRF)

Authentication is a crucial aspect of securing APIs. In Django Rest Framework (DRF), multiple authentication methods can be implemented to protect API endpoints from unauthorized access. This section covers:

  1. Introduction to Authentication

  2. Using Token Authentication

  3. Implementing JWT Authentication

1. Introduction to Authentication

Authentication is the process of verifying the identity of users accessing an API. DRF provides several authentication methods to ensure only authorized users interact with API endpoints.

Key Authentication Methods in DRF:

  • Session Authentication – Uses Django’s built-in session management.

  • Token Authentication – Uses unique tokens assigned to users for API access.

  • JWT (JSON Web Token) Authentication – Provides stateless authentication using encoded tokens.

In this guide, we focus on Token Authentication and JWT Authentication.

2. Using Token Authentication

What is Token Authentication?

Token-based authentication assigns each user a unique token, which they must send with API requests for authentication.

Configuration in DRF:

🔹 Step 1: Enable Token Authentication in settings.py

Add the following configuration in settings.py:

REST_FRAMEWORK = {

    ‘DEFAULT_AUTHENTICATION_CLASSES’: [

        ‘rest_framework.authentication.TokenAuthentication’,

    ],

}

🔹 Step 2: Install and Migrate Token Authentication

Add the following code in bookstore/settings.py.
INSTALLED_APPS = [

    …

    ‘rest_framework.authtoken’

Run the server and migrate

python manage.py migrate

Note:We migrate here to create a table to store token of each user.

🔹 Step 3: Create a Token for a User

To generate a token for a user, follow the steps:

Start the server ,and visit http://127.0.0.1:8000/admin .click on Tokens.

Now ,token has been generated successfully.

🔹 Step 5: Making API Requests with Token Authentication using postman

Clients must include the token in the Authorization header when making API requests.For example:

Set Up Your URL and Request Type

  • In Postman, create a new request.
  • Method: GET

URL: http://127.0.0.1:8000/api/books/custom-list/  (Make sure you include the trailing slash / if your Django URL configuration requires it)

✅ Add Authorization Header

  1. Go to the “Headers” tab.
  2. Add a new header:

Key: Authorization

Value: Token <YourToken>

 

  • Replace <YourToken> with your actual token.
  • Example:

Authorization: Token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9…

Exercise:

  • Enable SessionAuthentication and BasicAuthentication in settings.py.

  • Try accessing the API in the browser and Postman.

  • Log in and test how each method works.

Course Video in English