Skip to content

A tutorial for user authentication between a django backend and react frontend using jwt

Notifications You must be signed in to change notification settings

seankwarren/Django-React-jwt-authentication

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

28 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Table of contents

Introduction

This tutorial will walk through the process of implementing user authentication between a Django backend and a React frontend using JSON Web Tokens (JWT) with the help of jwt.io. We'll start by setting up a basic Django backend with a user authentication system, then create a React frontend and integrate it with our backend. Finally, we'll implement JWT-based authentication to secure our web application, and access protected data. By the end of this tutorial, you'll have a solid understanding of how to use JWT to implement user authentication in a full-stack web application. For more discussion on why or why not to use JWT visit here.

What is JWT?

JWT stands for JSON Web Token. It is an open standard for securely transmitting information between parties as a JSON object. In the context of web applications, JWTs are commonly used for authentication and authorization purposes.

JWTs are useful because they allow a user to authenticate once and then securely transmit that authentication information between different parts of an application. This can eliminate the need to constantly re-authenticate a user, which can improve the overall user experience. JWTs are also stateless, which means that no server-side state needs to be stored, making them a good fit for distributed applications.

Django Rest Framework's built-in JWT functionality provides an easy way to use JWTs for authentication and authorization. When a user logs in, a JSON web token is generated by the server and sent to the client. The client then includes the token in subsequent requests to the server to prove that it has already been authenticated.

When a request with a JWT is received by the server, the server validates the token by checking its signature and decoding the payload. If the token is valid, the server uses the information in the payload to authorize the request. If the token is not valid, the request is denied.

Security is a critical aspect of using JWT for authentication and authorization. JWT tokens can potentially be intercepted and used by an attacker to gain unauthorized access to sensitive data or actions. It's important to properly secure tokens to prevent this. The tokens should be sent over HTTPS, and they should be properly validated to ensure they haven't been tampered with. It's also important to set a short expiration time for the access token to minimize the risk of an attacker using it. Django Rest Framework's JWT implementation includes measures to mitigate these risks, but it's still important to follow best practices to ensure the security of your application.

For more information on securing JWT in, see this post on JWT Best Practice.


Backend

Boilerplate Setup

To start, we need a new Django project. In a shell, navigate to the directory you want to contain your project, and run
django-admin startproject backend

Enter the new project folder:
cd backend

Before installing Django, you need to make sure that pipenv is installed. If you haven't installed it already, you can run:
pip install pipenv

Then, launch a virtual environment by calling
pipenv shell
This creates a new virtual environment tied to this directory.

First we need to install django in the new virtual env by running:
pip install django

Now we can create our app:
python manage.py startapp base

Make sure to run this command in the backend directory.

If you are using VSCode as your IDE, from here you can open the directory with code .

Now that there is a template in place, we are ready to start making changes. We want all the authentication api functionality to reside together, and to provide more separation for this functionality, we will create a new folder inside of /base called /api.

Now if everything has been setup correctly, when you run python manage.py runserver, you should be able to see the server running on http://127.0.0.1:8000



Creating a view and routing it

Our goal here is to create a view that returns two API routes that will be used for sending user login details and receiving authentication tokens.

The first thing we want to do is create a new view and link it in the urls. In the api folder create two new files: urls.py and views.py. This urls.py folder will contain all of our user auth api routes; we will include it in the main url config file /base/urls.py later.

This is what the directory structure should look like:

backend
├── Pipfile
├── Pipfile.lock
├── README.md
├── backend
│   ├── README.md
│   ├── __init__.py
│   ├── asgi.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── base
│   ├── README.md
│   ├── __init__.py
│   ├── admin.py
│   ├── api
│   │   ├── README.md
│   │   ├── urls.py
│   │   └── views.py
│   ├── apps.py
│   ├── migrations
│   │   ├── README.md
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── db.sqlite3
└── manage.py

In views.py create a new view that returns all the possible routes, here, we are going to have two routes: one for sending user login details and receiving authentication tokens /api/token, and one for sending a refresh token and receiving new authentication tokens /api/token/refresh.

from django.http import JsonResponse
def get_routes(request):
   routes = [
       '/api/token',
       '/api/token/refresh'
   ]
   return JsonResponse(routes, safe=False)

Note: The safe=False allows us to receive and display non-Json data

To link this view to an accessible url, we need to complete the urls.py file in our /api directory.
/api/urls.py:

from django.urls import path
from . import views

urlpatterns = [
   path('', views.get_routes),
]

Now to include the new url configuration in the app’s main url config file /backend/urls.py, we need to import include and add a new path pointing to the /base/api/urls.py file
/backend/urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
   path('admin/', admin.site.urls),
   path('api/', include('base.api.urls'))
]

Now if you navigate to http://127.0.0.1:8000/api you should see these two routes displayed.



Adding Django Rest Framework

Now we want to use the Django Rest Framework for our API, the documentation for usage can be found here. To install make sure the virtual env is active and run

pip install djangorestframework

and modify the /backend/settings.py file

INSTALLED_APPS = [
    ...
    'rest_framework',
]

We can change our view to use the django rest framwork by changing the response to use a DjangoRestFramework Response class instead of the default javascript JsonResponse. Because this is a function based view, we also need to instruct it what kind of view we want to render with a decorator.

from rest_framework.response import Response
from rest_framework.decorators import api_view

@api_view(['GET'])
def get_routes(request):
    """returns a view containing all the possible routes"""
    routes = [
        '/api/token',
        '/api/token/refresh'
    ]

    return Response(routes)

If everything is configured correctly, you should see a new view at http://127.0.0.1:8000/api with an output that looks like this:

HTTP 200 OK
Allow: OPTIONS, GET
Content-Type: application/json
Vary: Accept

[
    "/api/token",
    "/api/token/refresh"
]


Adding JWT - creating login and refresh views

Luckily, django rest framework has JWT built in. Following the documentation, to add it, we need to install it in the virtual env:
pip install djangorestframework-simplejwt

and configure it to be the default authentication behavior for django rest framework in the settings.py file by adding this setting:

REST_FRAMEWORK = {
    ...
    'DEFAULT_AUTHENTICATION_CLASSES': (
        ...
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    )
    ...
}

and add two urls for the login and refresh routes in /base/api/urls.py

the new urls.py file should look like this:

from django.urls import path
from . import views

from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
)

urlpatterns = [
    path('', views.get_routes),
    path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]

Verify jwt is working by first migrating the changes to the data model with
python manage.py migrate
then creating a superuser with
python manage.py createsuperuser.

Now when visiting http://127.0.0.1:8000/api/token/ you should see input fields for a username and password. Login using the superuser login you just created.

After POSTing your login credentials, you should receive a refresh and access token that looks like this:

HTTP 200 OK
Allow: POST, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "refresh": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTY3NjU5MTcyMywiaWF0IjoxNjc2NTA1MzIzLCJqdGkiOiI2MTBlM2I4NTk3ZGQ0NGQ2YTk3MWViZTEwYzQzOTg3YiIsInVzZXJfaWQiOjF9.P5ps5AOBp25_HoeiatbC7_LZjoBBb0SxukvcpyvuaqI",
    "access": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjc2NTA1NjIzLCJpYXQiOjE2NzY1MDUzMjMsImp0aSI6IjUxMTUzYTRiNmJkNjQyNTY4NDMzN2UyZjEyN2M2YTkwIiwidXNlcl9pZCI6MX0.O1n1TppJFk0KO8rUco1UWPaOcCyxaRPFOmIZv0Pte18"
}

Copy the refresh token you were just provided and then navigate to http://127.0.0.1:8000/api/token/refresh, where you should see an input field for the refresh token. Paste and submit the refresh token. You should receive a new access token from the server if everything has worked.



Customizing JWT behavior

There is a lot of potential customization to the behavior of JWT that can be found here, but I want to highlight a few that are of interest to us:

"ACCESS_TOKEN_LIFETIME": timedelta(minutes=5), # Specifies how long access tokens are valid. Typically use a lower value for higher security but more network overhead. Changing this will be useful for testing.

"REFRESH_TOKEN_LIFETIME": timedelta(days=1), # Specifies how long refresh tokens are valid, this corresponds to how longer a user can remain logged in while not actively refreshing their tokens. Ex: if a user closes the tab for 22 hours, on reopening, the old refresh token would still be able to fetch a valid access token, continuing their authentication. Changing this will be useful for testing.

"ROTATE_REFRESH_TOKENS": False, # When set to True, if a refresh token is submitted to the TokenRefreshView, a new refresh token will be returned along with the new access token. This provides a way to keep a rolling authentication while a client is open.

"BLACKLIST_AFTER_ROTATION": False, # Causes refresh tokens submitted to the TokenRefreshView to be added to the blacklist. This prevents the scenario where a bad actor can use old refresh tokens to request their own new authentication tokens.

While ACCESS_TOKEN_LIFETIME and REFRESH_TOKEN_LIFETIME can remain as default for now, we want to change both ROTATE_REFRESH_TOKENS and BLACKLIST_AFTER_ROTATION to True. Using the default settings from the documentation, we can add this section to the settings.py file with the new values.

from datetime import timedelta
...

SIMPLE_JWT = {
    "ACCESS_TOKEN_LIFETIME": timedelta(minutes=5),
    "REFRESH_TOKEN_LIFETIME": timedelta(days=1),
    "ROTATE_REFRESH_TOKENS": True,
    "BLACKLIST_AFTER_ROTATION": True,
    "UPDATE_LAST_LOGIN": False,

    "ALGORITHM": "HS256",
    "SIGNING_KEY": SECRET_KEY,
    "VERIFYING_KEY": "",
    "AUDIENCE": None,
    "ISSUER": None,
    "JSON_ENCODER": None,
    "JWK_URL": None,
    "LEEWAY": 0,

    "AUTH_HEADER_TYPES": ("Bearer",),
    "AUTH_HEADER_NAME": "HTTP_AUTHORIZATION",
    "USER_ID_FIELD": "id",
    "USER_ID_CLAIM": "user_id",
    "USER_AUTHENTICATION_RULE": "rest_framework_simplejwt.authentication.default_user_authentication_rule",

    "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",),
    "TOKEN_TYPE_CLAIM": "token_type",
    "TOKEN_USER_CLASS": "rest_framework_simplejwt.models.TokenUser",

    "JTI_CLAIM": "jti",

    "SLIDING_TOKEN_REFRESH_EXP_CLAIM": "refresh_exp",
    "SLIDING_TOKEN_LIFETIME": timedelta(minutes=5),
    "SLIDING_TOKEN_REFRESH_LIFETIME": timedelta(days=1),
}

To enable the blacklist, we need to add the blacklist app to our list of installed apps and migrate the assocaited data model changes:

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

python manage.py migrate

Now when you visit http://127.0.0.1:8000/api/token/ and login, and use the refresh token at http://127.0.0.1:8000/api/token/refresh/, you should receive both a new access token and a new refresh token. You can also test the blacklist is functioning by trying to submit the same refresh token a second time. You should receive a response like this, indicating that token has already been used.

HTTP 401 Unauthorized
Allow: POST, OPTIONS
Content-Type: application/json
Vary: Accept
WWW-Authenticate: Bearer realm="api"

{
    "detail": "Token is blacklisted",
    "code": "token_not_valid"
}

Customizing JWT token - include the username

JWT tokens can be customized to include specific data. If you paste an access token into the debugger at jwt.io, you can see the payload data that it contains. This data usually includes the user_id, but what if we wanted to include the username as well without having to make a separate request to the server?

To do this, we can create a custom serializer that extends the TokenObtainPairSerializer class and overrides the get_token() method. In this method, we can add a new claim to the token, such as the username. The modified serializer looks like this:

from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView

class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)
        token['username'] = user.username
        return token

Next, we need to create a custom view that uses our custom serializer instead of the default one. We can do this by creating a new view that extends the TokenObtainPairView class and sets its serializer_class attribute to our custom serializer. Here's what the new view looks like:

from .serializers import MyTokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView

class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer

Finally, we need to modify the URL to point to our new custom view. In our urls.py file, we replace TokenObtainPairView with MyTokenObtainPairView:

from django.urls import path
from .views import MyTokenObtainPairView
from rest_framework_simplejwt.views import TokenRefreshView

urlpatterns = [
    path('token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]

Allowing Frontend Access with CORS

To allow requests from our frontend application, we need to set up Cross-Origin Resource Sharing (CORS) configuration for our Django project. The django-cors-headers library provides a simple way to enable CORS in our application.

First, we need to install the django-cors-headers package by running the following command:
pip install django-cors-headers

Next, add corsheaders to the INSTALLED_APPS list in the settings.py file:

INSTALLED_APPS = [
    ...,
    "corsheaders",
    ...,
]

After that, add the CorsMiddleware to the MIDDLEWARE list:

MIDDLEWARE = [
    ...,
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.common.CommonMiddleware",
    ...,
]

Now we can configure the allowed origins in the settings.py file. For simplicity, we will allow all origins using the following setting:

CORS_ALLOW_ALL_ORIGINS = True

Note that this setting should be modified to specify the allowed origins during deployment for security reasons.

With these settings, our Django backend is ready to receive requests from a frontend application.



Frontend

To create the frontend for our app, we will use npx create-react-app frontend to set up a new React application. This command generates a starter project with some boilerplate code that we can customize to fit our needs.

We are going to use npx create-react-app frontend for a boilerplate of our react application.

To get started, navigate to the new directory with cd frontend. Next, we'll clean up some of the extra files that we won't be using, such as webVitals and the logo. In the /src folder, delete App.css, App.test.js, logo.svg, reportWebVitals.js, and setupTests.js. Then modify App.js and index.js to remove all references to these deleted files:

App.js:

function App() {
  return (
    <div className="App">
    </div>
  );
}

export default App;

index.js:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

At this point, the directory should have the following structure:

frontend
├── node_modules
├── package-lock.json
├── package.json
├── public
│   ├── favicon.ico
│   ├── index.html
│   ├── logo192.png
│   ├── logo512.png
│   ├── manifest.json
│   └── robots.txt
└── src
    ├── App.js
    ├── index.css
    └── index.js

Now we're ready to start building our application. We'll begin by adding some folders for organization. To start, let's create a /pages folder to contain our homepage (HomePage.js) and login page (LoginPage.js). We'll also need a header shared in common on both pages, so we'll add a /components folder to contain it and other shared components. To manage state, we'll create a /context/AuthContext.js file, which will use React's built-in Context API. Finally, we'll create a /utils folder for shared logic.

After all these changes, the directory should look like this:

frontend
├── node_modules
├── package-lock.json
├── package.json
├── public
│   ├── favicon.ico
│   ├── index.html
│   ├── logo192.png
│   ├── logo512.png
│   ├── manifest.json
│   └── robots.txt
└── src
    ├── App.js
    ├── components
    │   └── Header.js
    ├── context
    │   └── AuthContext.js
    ├── index.css
    ├── index.js
    ├── pages
    │   ├── HomePage.js
    │   └── LoginPage.js
    └── utils

With this basic structure in place, we're ready to start building the frontend of our app.


Setting up webpages

Lets start with a simple homepage. This page should only be visible to users who are logged in, but for now, we'll hardcode an isAuthenticated value for demonstration purposes only.

HomePage.js:

import React from 'react'

const HomePage = () => {
    const isAuthenticated = false;
    return (
        isAuthenticated ? (
        <div>
            <p>You are logged in to the homepage!</p>
        </div>
        ):(
        <div>
            <p>You are not logged in, redirecting...</p>
        </div>
        )
    )
}

export default HomePage

next we can create a simple login page, but it wont work yet without a proper loginUser function, we'll define that later:

LoginPage.js:

import React from 'react'

const LoginPage = () => {

    let loginUser = (e) => {
        e.preventDefault()
    }

    return (
        <div>
            <form onSubmit={loginUser}>
                <input type="text" name="username" placeholder="Enter username"/>
                <input type="password" name="password" placeholder="enter password"/>
                <input type="submit"/>
            </form>
        </div>
    )
}

export default LoginPage

the Header component will responsible for displaying the navigation links and user information, and it is included in the App component so that it appears on every page. Again we are using a filler function for handling logging out a user for now:

Header.js:

import React, { useState } from 'react'
import { Link } from 'react-router-dom'

const Header = () => {
    let [user, setUser] = useState(null)
    let logoutUser = (e) => {
        e.preventDefault()
    }
    return (
        <div>
            <Link to="/">Home</Link>
            <span> | </span>
            {user ? (
                <p onClick={logoutUser}>Logout</p>
            ) : (
                <Link to="/login" >Login</Link>
            )}
            {user && <p>Hello {user.username}!</p>}

        </div>
    )
}

export default Header

We need to setup all the url routing for these pages in App.js. To do this we need to install the react-router-dom package with npm install react-router-dom. It is used to handle routing, its documentation can be found here.

App.js:

import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'

import HomePage from './pages/HomePage'
import LoginPage from './pages/LoginPage'
import Header from './components/Header'

function App() {
    return (
        <div className="App">
            <Router>
                <Header/>
                <Routes>
                    <Route path="/" element={<HomePage/>} />
                    <Route path="/login" element={<LoginPage/>}/>
                </Routes>
            </Router>
        </div>
    );
}

export default App;

We are finally ready to launch the frontend. Make sure youre in the /frontend directory and run npm start in the console. A development server should launch on localhost:3000.

you should be able to see the homepage, and if you click the Login link in the header, you should be directed to the login page.



Protected routes

When a user visits the homepage without being authenticated, they should be redirected to the login page. This type of page is called a private route, one that requires authentication to view. To add private routes, we first need to define a component in utils/PrivateRoute.js.

import { Navigate } from 'react-router-dom'
import { useState } from 'react'

const PrivateRoute = ({children, ...rest}) => {
    let [user, setUser] = useState(null)

    return !user ? <Navigate to='/login'/> : children;
}

export default PrivateRoute;

This component checks if a client is authenticated. If so, the rendering continues uninterrupted. Otherwise, the client is redirected to the login page. We've used a separate state to store the user here, but we want this user state to match the user state in the header. This is where context state management comes in, and we'll cover that later.

To protect a route, we just need to wrap the Route component in a <PrivateRoute> component like so:

<Routes>
    ...
    <Route path="/" element={<PrivateRoute><HomePage/></PrivateRoute>} />
    ...
</Routes>

This protects the homepage route, meaning a user cannot access the page until they are authenticated, and will instead be redirected to the login page.

Here's the updated App.js file with a protected homepage:

import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'

import HomePage from './pages/HomePage'
import LoginPage from './pages/LoginPage'
import Header from './components/Header'

import PrivateRoute from './utils/PrivateRoute'


function App() {
  return (
    <div className="App">
        <Router>
            <Header/>
            <Routes>
                <Route path="/" element={<PrivateRoute><HomePage/></PrivateRoute>} />
                <Route path="/login" element={<LoginPage/>}/>
            </Routes>
        </Router>
    </div>
  );
}

export default App;

Now you should be unable to load the homepage until a user is authenticated, and will instead be redirected to the login page.


AuthContext - state management

We want to save the authentication tokens and user state and use it throughout the application, so to avoid prop drilling or other more complicated options, we'll use the useContext hook built into React.

createContext()

createContext() is a function provided by the React library that allows you to create a context object. This object provides a way to pass data between components without having to pass props down through the component tree. It consists of a provider component that wraps the other components and passes data down to them, and a consumer component that accesses the data passed down from the provider.

In this case, we use the createContext() function to create an AuthContext object, which we then export and use as a shared state across our application. We define the initial state and any methods that we want to share in the AuthProvider component, and then wrap our components with this provider so that they have access to this shared state.

To start we will define the state we know we want shared across our application in an AuthProvider component, including a user, authTokens, loginUser method and logoutUser method.

import { createContext, useState } from 'react'

const AuthContext = createContext()

export default AuthContext;

export const AuthProvider = ({children}) => {

    let [user, setUser] = useState(null)
    let [authTokens, setAuthTokens] = useState(null)

    let loginUser = async (e) => {
        e.preventDefault()
    }

    let logoutUser = (e) => {
        e.preventDefault()
    }

    let contextData = {
        user: user,
        authTokens: authTokens,
        loginUser: loginUser,
        logoutUser: logoutUser,
    }

    return(
        <AuthContext.Provider value={contextData}>
            {children}
        </AuthContext.Provider>
    )
}

Then we can provide this state to the other components by wrapping them in an <AuthProvider> component:

App.js

import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'

import { AuthProvider } from './context/AuthContext'

import HomePage from './pages/HomePage'
import LoginPage from './pages/LoginPage'
import Header from './components/Header'

import PrivateRoute from './utils/PrivateRoute'


function App() {
    return (
        <div className="App">
            <Router>
                <AuthProvider>
                <Header/>
                <Routes>
                    <Route path="/" element={
                        <PrivateRoute>
                            <HomePage/>
                        </PrivateRoute>}/>
                    <Route path="/login" element={<LoginPage/>}/>
                </Routes>
                </AuthProvider>
            </Router>
        </div>
    );
}

export default App;

useContext()

useContext() is a hook provided by the React library that allows you to consume the data and methods passed down by a context provider. It takes in a context object created by createContext() and returns the current value of the context.

In our application, we use useContext() to access the shared state and methods defined in our AuthContext object. We call useContext(AuthContext) inside our components to access the current user state, authentication tokens, login function, and logout function. This allows us to avoid prop drilling and pass data and methods down from the top-level component to the components that need them.

E.g.

let { user, loginUser } = useContext(AuthContext)

We need to make this change in 4 places:

  1. Header.js, after adjusting to use the shared context and logoutUser method, looks like:
import React, { useContext } from 'react'
import { Link } from 'react-router-dom'
import AuthContext from '../context/AuthContext'

const Header = () => {
    let { user, logoutUser } = useContext(AuthContext)

    return (
        <div>
            <Link to="/">Home</Link>
            <span> | </span>
            {user ? (
                <p onClick={logoutUser}>Logout</p>
            ) : (
                <Link to="/login" >Login</Link>
            )}
            {user && <p>Hello {user.username}!</p>}

        </div>
    )
}

export default Header
  1. LoginPage.js, after adjusting to use the shared loginUser method, looks like:
import React, {useContext} from 'react'
import AuthContext from '../context/AuthContext'

const LoginPage = () => {

    let {loginUser} = useContext(AuthContext)

    return (
        <div>
            <form onSubmit={loginUser}>
                <input type="text" name="username" placeholder="Enter username"/>
                <input type="password" name="password" placeholder="enter password"/>
                <input type="submit"/>
            </form>
        </div>
    )
}

export default LoginPage
  1. Homepage.js is also adjusted to use the AuthContext for user state:
import React, { useContext } from 'react'
import AuthContext from '../context/AuthContext';

const HomePage = () => {
    const { user } = useContext(AuthContext);

    return (user ? (
        <div>
            <p>You are logged in to the homepage!</p>
        </div>
        ):(
        <div>
            <p>You are not logged in, redirecting...</p>
        </div>
        )
    )
}

export default HomePage
  1. The last place to make this change is in PrivateRoute.js
import { Navigate } from 'react-router-dom'
import { useContext } from 'react'
import AuthContext from '../context/AuthContext';

const PrivateRoute = ({children, ...rest}) => {
    let { user } = useContext(AuthContext)

    return !user ? <Navigate to='/login'/> : children;
}

export default PrivateRoute;

we can test this is working by changing the state of user in AuthContext.js and verifying that our header now shows a greeting to the user and offers a logout option instead of a login option.

let [user, setUser] = useState({username:'Sean'})

return the state to null after testing.

Login method

The loginUser method is responsible for handling the user's login attempt by submitting a POST request to the backend server with the user's login credentials. The response should contain auth tokens, which need to be decoded so that the payload data can be read. The jwt-decode package can be installed to help with this. npm install jwt-decode

If the POST request is successful, the newly received tokens and the successfully logged-in user should be stored in state, and the tokens saved in local storage. The user should then be redirected to their homepage. If there is an error, an alert should be shown.

Here's the code for the entire AuthProvider component, with the new method:

import { createContext, useState } from 'react'
import jwtDecode from 'jwt-decode';
import { useNavigate } from 'react-router-dom'

const AuthContext = createContext()

export default AuthContext;

export const AuthProvider = ({children}) => {

    let [user, setUser] = useState(null)
    let [authTokens, setAuthTokens] = useState(null)

    const navigate = useNavigate()

    let loginUser = async (e) => {
        e.preventDefault()
        const response = await fetch('http://127.0.0.1:8000/api/token/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({username: e.target.username.value, password: e.target.password.value })
        });

        let data = await response.json();

        if(data){
            localStorage.setItem('authTokens', JSON.stringify(data));
            setAuthTokens(data)
            setUser(jwtDecode(data.access))
            navigate('/')
        } else {
            alert('Something went wrong while loggin in the user!')
        }
    }

    let logoutUser = (e) => {
        e.preventDefault()
    }

    let contextData = {
        user: user,
        authTokens: authTokens,
        loginUser: loginUser,
        logoutUser: logoutUser,
    }

    return(
        <AuthContext.Provider value={contextData}>
            {children}
        </AuthContext.Provider>
    )
}

After submitting the superuser credentials on the login page, if the request is successful, the user should be logged in and redirected to the home page.

Logout method

The logout link isn't working yet, so let's fix that. To logout a user, we need to - Clear the localStorage by removing the stored authentication tokens - Update the state of the authTokens and user to null, effectively logging the user out - Redirect the user is redirected to the login page using the navigate method from react-router-dom:

let logoutUser = (e) => {
    e.preventDefault()
    localStorage.removeItem('authTokens')
    setAuthTokens(null)
    setUser(null)
    navigate('/login')
}

Now when you click on the logout link, you should be logged out and redirected to the login page. Confirm the localStorage is cleared in the storage tab of the developer tools.


Keeping a user logged in after refresh

After submitting login details and being redirected to the homepage, refreshing the page logs the user out. To prevent this, we can use JSON Web Tokens (JWT) stored in localStorage to automatically log the user back in without requiring login credentials.

To achieve this, we need to update the initial state of the user and authTokens variables in AuthContext.js to check the localStorage for authTokens before setting them to null if none are found. We can use a callback function in the useState hook to ensure that this logic is only executed once on the initial load of AuthProvider, and not on every rerender.

Here are the updated lines of code:

AuthContext.js

let [user, setUser] = useState(() => (localStorage.getItem('authTokens') ? jwtDecode(localStorage.getItem('authTokens')) : null))
let [authTokens, setAuthTokens] = useState(() => (localStorage.getItem('authTokens') ? JSON.parse(localStorage.getItem('authTokens')) : null))

After submitting login credentials, redirecting to the homepage, and refreshing the page, the user should remain logged in.


UpdateToken method - Refreshing the access token

The access token, as currently configured, has a limited lifetime of 5 minutes, after which a new one must be generated using the refresh token. To handle this, we need to create an updateToken method. This is the setting of interest:

...
"ACCESS_TOKEN_LIFETIME": timedelta(minutes=5),
...

The updateToken method sends a POST request to http://127.0.0.1:8000/api/token/refresh/ containing the refresh token, and receives a new access token and refresh token to save in localStorage and update the context state. If an invalid refresh token is used, the user is logged out. Here is the code for the updateToken method:

const updateToken = async () => {
        const response = await fetch('http://127.0.0.1:8000/api/token/refresh/', {
            method: 'POST',
            headers: {
                'Content-Type':'application/json'
            },
            body:JSON.stringify({refresh:authTokens?.refresh})
        })

        const data = await response.json()
        if (response.status === 200) {
            setAuthTokens(data)
            setUser(jwtDecode(data.access))
            localStorage.setItem('authTokens',JSON.stringify(data))
        } else {
            logoutUser()
        }

        if(loading){
            setLoading(false)
        }
    }

Refreshing the Token on an Interval

To keep the user authenticated, we need to refresh their access token before it expires. In our case, we will refresh the token every 4 minutes to avoid the possibility of a slow server response causing the user to be logged out. This approach has obvious drawbacks, and surely a better and more popular approach would be to refresh these tokens on every call to the server with Axios interceptors. I plan to explore this in the future, but for now we will update the tokens on an interval using the useEffect hook. Here is the code for that useEffect hook:

let [loading, setLoading] = useState(true)

useEffect(()=>{

        const REFRESH_INTERVAL = 1000 * 60 * 4 // 4 minutes
        let interval = setInterval(()=>{
            if(authTokens){
                updateToken()
            }
        }, REFRESH_INTERVAL)
        return () => clearInterval(interval)

    },[authTokens])

The useEffect hook uses JavaScript's built-in setInterval function to execute a callback function at a set interval in milliseconds. We need to clear the existing interval when the hook is triggered again to avoid multiple intervals being created. We also need to track when the page is loading using the loading state, which is initially set to true.


Our new AuthContext.js:

import { createContext, useState, useEffect } from 'react'
import jwtDecode from 'jwt-decode';
import { useNavigate } from 'react-router-dom'

const AuthContext = createContext()

export default AuthContext;

export const AuthProvider = ({children}) => {

    let [user, setUser] = useState(() => (localStorage.getItem('authTokens') ? jwtDecode(localStorage.getItem('authTokens')) : null))
    let [authTokens, setAuthTokens] = useState(() => (localStorage.getItem('authTokens') ? JSON.parse(localStorage.getItem('authTokens')) : null))
    let [loading, setLoading] = useState(true)

    const navigate = useNavigate()

    let loginUser = async (e) => {
        e.preventDefault()
        const response = await fetch('http://127.0.0.1:8000/api/token/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({username: e.target.username.value, password: e.target.password.value })
        });

        let data = await response.json();

        if(data){
            localStorage.setItem('authTokens', JSON.stringify(data));
            setAuthTokens(data)
            setUser(jwtDecode(data.access))
            navigate('/')
        } else {
            alert('Something went wrong while logging in the user!')
        }
    }

    let logoutUser = (e) => {
        e.preventDefault()
        localStorage.removeItem('authTokens')
        setAuthTokens(null)
        setUser(null)
        navigate('/login')
    }

    const updateToken = async () => {
        const response = await fetch('http://127.0.0.1:8000/api/token/refresh/', {
            method: 'POST',
            headers: {
                'Content-Type':'application/json'
            },
            body:JSON.stringify({refresh:authTokens?.refresh})
        })

        const data = await response.json()
        if (response.status === 200) {
            setAuthTokens(data)
            setUser(jwtDecode(data.access))
            localStorage.setItem('authTokens',JSON.stringify(data))
        } else {
            logoutUser()
        }

        if(loading){
            setLoading(false)
        }
    }

    let contextData = {
        user:user,
        authTokens:authTokens,
        loginUser:loginUser,
        logoutUser:logoutUser,
    }

    useEffect(()=>{
        const REFRESH_INTERVAL = 1000 * 60 * 4 // 4 minutes
        let interval = setInterval(()=>{
            if(authTokens){
                updateToken()
            }
        }, REFRESH_INTERVAL)
        return () => clearInterval(interval)

    },[authTokens])

    return(
        <AuthContext.Provider value={contextData}>
            {children}
        </AuthContext.Provider>
    )
}

Edge cases:

Let's consider an edge case where the REFRESH_TOKEN_LIFETIME setting on the backend is set to a short duration, say 5 seconds. After logging in, if a token refresh is triggered, you'll receive a 401 Unauthorized access response when a call is made to update the tokens. This is because the refresh token has expired, and login credentials are required to authenticate the user again. To simulate this edge case, you can set the token refresh interval to 10000 ms (10 seconds).

To ensure that a user is logged out and redirected to the login page when accessing a protected route with an expired access token, and is not logged out and redirected while waiting for a response to an updateToken request, we need to keep track of when the AuthProvider is first loaded. We can achieve this by initializing a new state variable, loading, to true:

let [loading, setLoading] = useState(true)

If the state is loading, we want to attempt to update the tokens at the beginning of the useEffect hook. This will fetch new refresh tokens where possible, and redirect users with invalid tokens back to the login screen:

useEffect(()=>{
    if(loading){
        updateToken()
    }
    ...
},[authTokens, loading])

Finally, at the end of the updateToken() function, set the loading state to false:

const updateToken = async () => {
    ...
    if(loading){
        setLoading(false)
    }
}

With this approach, we ensure that the user is logged out and redirected to the login page only when the access token has expired, and not while waiting for a response to an updateToken request.

User Permissions - control access to user-specific data

To control access to user-specific data, we need to extend the default Django User model by adding a Profile model with a one-to-one relationship. The Profile model will contain private information such as first name, last name, and email. We will display each user their own profile information when on the home page.

Setting up user-specific data in django

To start we need to return to the backend and add the Profile model to the models.py file:

models.py

from django.db import models
from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    email = models.EmailField()

    def __str__(self):
        return self.user.username

We also need a serializer for the new Profile model. Create a serializers.py file inside the /base directory. We define a simple serializer for User so we can nest it inside the ProfileSerializer:

serializers.py

from rest_framework import serializers
from base.models import *

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

class ProfileSerializer(serializers.ModelSerializer):
    user = UserSerializer(many=False, read_only=True)
    class Meta:
        model = Profile
        fields = ('user', 'first_name', 'last_name', 'email')

We make this data available via the /api route with a new view. We use a new decorator from the Django REST framework, @permission_classes to verify that the user is authenticated with request.user before any of the other code in the view is executed: (Documentation on permissions can be found here)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_profile(request):
    user = request.user
    profile = user.profile
    serializer = ProfileSerializer(profile, many=False)
    return Response(serializer.data)

then we can link this view in the urls.py file:

urlpatterns = [
    path('profile/', views.get_profile),
    ...
]

Testing user permissions - displaying private profile info

To test user permissions, we need to migrate the data model changes with:

python manage.py makemigrations

python manage.py migrate

You may need to delete all previous users or add null=True to the model fields to migrate the changes.

Create two users, each with associated profiles:

e.g.

username: "user1",
password: "password1",
profile: {
    first_name: "Sam",
    last_name: "Smith",
    email: "[email protected]"
}

username: "user2",
password: "password2",
profile: {
    first_name: "Tim",
    last_name: "Allen",
    email: "[email protected]"
}

If you try to access http://127.0.0.1:8000/api/profile now, you will get an "Unauthorized" response. By default, the GET request does not include any authentication details. To authenticate, we need to go back to the frontend and change our homepage to render these details specific to the authenticated user. We have defined a getProfile() function to fetch the profile data from the server, including our auth access token with the GET request. We have also added a state to store our profile data. (If this data were used in other places throughout the application, you may consider moving this to a context for shared state management.) Lastly, the useEffect hook is used to fetch the profile data once on the first load of the component, provided the blank dependency array.

HomePage.js

import React, { useState, useEffect, useContext } from 'react'
import AuthContext from '../context/AuthContext';

const HomePage = () => {
    const { authTokens, logoutUser } = useContext(AuthContext);
    let [profile, setProfile] = useState([])

    useEffect(() => {
        getProfile()
    },[])

    const getProfile = async() => {
        let response = await fetch('http://127.0.0.1:8000/api/profile', {
        method: 'GET',
        headers:{
            'Content-Type': 'application/json',
            'Authorization':'Bearer ' + String(authTokens.access)
        }
        })
        let data = await response.json()
        console.log(data)
        if(response.status === 200){
            setProfile(data)
        } else if(response.statusText === 'Unauthorized'){
            logoutUser()
        }
    }

    return (
        <div>
            <p>You are logged in to the homepage!</p>
            <p>Name: {profile.first_name} {profile.last_name}</p>
            <p>Email: {profile.email}</p>
        </div>
    )
}

export default HomePage

Now when you navigate to http://localhost:3000/login and login with (username: "user1", password: "password1") you should see the profile details for this user on the home page:

    Name: Sam Smith
    Email: [email protected]

and when you login to a different user (username: "user2", password: "password2") you should see their profile details:

    Name: Tim Allen
    Email: [email protected]