DEV Community

Muhammad Asif
Muhammad Asif

Posted on

Setting Up JWT Authentication in Django REST Framework

In this Post, we'll discuss how to set up JSON Web Token (JWT) authentication in Django REST Framework using the rest_framework_simplejwt package. JWT authentication is a secure and popular method for authenticating users in web applications.

Prerequisites

Before implementing JWT authentication, ensure you have the following installed and configured:

  • Django
  • Django REST Framework
  • rest_framework_simplejwt

Configuration

  1. Install Dependencies

Make sure you have rest_framework and rest_framework_jwt installed. If not, you can install them using pip:

   pip install djangorestframework
   pip install djangorestframework-jwt
Enter fullscreen mode Exit fullscreen mode
  1. Django Settings Configuration

In your Django project's settings (settings.py), configure the REST framework with JWT authentication by adding the following:

   REST_FRAMEWORK = {
       "NON_FIELD_ERRORS_KEY": "errors",
       "DEFAULT_AUTHENTICATION_CLASSES": (
           'rest_framework.authentication.BasicAuthentication',
           'rest_framework_simplejwt.authentication.JWTAuthentication',
       ),
   }
Enter fullscreen mode Exit fullscreen mode

This code snippet tells Django REST Framework to use JWT authentication as the default authentication mechanism.

  1. URL Configuration

In your urls.py file, set up the endpoints for token management:

   from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView, TokenVerifyView

   urlpatterns = [
       path('gettoken/', TokenObtainPairView.as_view(), name="get_token"),
       path('refreshtoken/', TokenRefreshView.as_view(), name="refresh_token"),
       path('verifytoken/', TokenVerifyView.as_view(), name="verify_token"),
   ]
Enter fullscreen mode Exit fullscreen mode

These endpoints will be used to obtain, refresh, and verify JWT tokens.

  1. Authentication Logic

In your authentication logic, such as a login view, you can generate and return JWT tokens upon successful user authentication. Here's a sample code snippet:

   from rest_framework_simplejwt.tokens import RefreshToken
   from django.contrib.auth import login as dj_login

   if user is not None:
       dj_login(request, user)
       refresh = RefreshToken.for_user(user)
       serializer = AccountSerializer(user)
       return Response({
           "access_token": str(refresh.access_token),
           "refresh_token": str(refresh),
           'data': serializer.data
       }, status=status.HTTP_200_OK)
   else:
       return Response({'error': 'Invalid credentials'}, status=400)
Enter fullscreen mode Exit fullscreen mode

This code logs in the user, generates a new access token and refresh token, and returns them in the response along with user data upon successful authentication. If authentication fails, it returns an error message.

5.JavaScript Code Example:

const jwtToken = "YOUR_JWT_TOKEN"; // Replace with your actual JWT token
const apiUrl = "http://your_domain/verifytoken/"; // Replace with your verification endpoint URL

// Function to verify the JWT token
async function verifyToken(token) {
  try {
    const response = await fetch(apiUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`,
      },
    });

    if (response.status === 200) {
      console.log("Token is valid");
    } else {
      console.error("Token verification failed");
    }
  } catch (error) {
    console.error("An error occurred during token verification:", error);
  }
}

// Call the verifyToken function with your JWT token
verifyToken(jwtToken);
Enter fullscreen mode Exit fullscreen mode

Replace "YOUR_JWT_TOKEN" with the actual JWT token you want to verify, and "http://your_domain/verifytoken/" with the URL of your Django verification endpoint.

Top comments (0)