Setting Up JWT Authentication in Django REST Framework
Tags: django, api, python, djangorestframework
Published: 2023-09-19 05:15:27

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:

   ```python
   pip install djangorestframework
   pip install djangorestframework-jwt
   ```

2. **Django Settings Configuration**

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

   ```python
   REST_FRAMEWORK = {
       "NON_FIELD_ERRORS_KEY": "errors",
       "DEFAULT_AUTHENTICATION_CLASSES": (
           'rest_framework.authentication.BasicAuthentication',
           'rest_framework_simplejwt.authentication.JWTAuthentication',
       ),
   }
   ```

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

3. **URL Configuration**

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

   ```python
   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"),
   ]
   ```

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

4. **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:

   ```python
   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)
   ```

   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:**
```javascript
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);
```

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.