JSON Web Token(JWT):
JSON Web Token is a digitally signed and secured token for user validation. The JWT is constructed with 3 important parts:
- Header
- Payload
- Signature
Create ReactJS Application:
Let's create a ReactJS application to accomplish our demo.
npx create-react-app name-of-your-app
Configure React Bootstrap Library:
Let's install the React Bootstrap library
npm install react-bootstrap bootstrap
Now add the bootstrap CSS reference in 'index.js'.
src/index.js:
import 'bootstrap/dist/css/bootstrap.min.css'
Create A React Component 'Layout':
Let's add a React component like 'Layout' in 'components/shared' folders(new folders).
src/components/shared/Layout.js:
import Navbar from "react-bootstrap/Navbar"; import { Container } from "react-bootstrap"; import Nav from "react-bootstrap/Nav"; const Layout = ({ children }) => { return ( <> <Navbar bg="primary" variant="dark"> <Navbar.Brand> <Nav.Link >Auth Demo</Nav.Link> </Navbar.Brand> </Navbar> <Container>{children}</Container> </> ); }; export default Layout;
- (Line: 7-11) Rendered the React Bootstrap Navbar component.
- (Line: 12) Using component 'children' property renders all other page components.
src/App.js:
import logo from "./logo.svg"; import "./App.css"; import Layout from "./components/shared/Layout"; function App() { return ( <> <Layout>Hi Welcome</Layout> </> ); } export default App;
Install React Router Dom Package:
Let's install the react-router package.
npm i react-router-dom
In the 'index.js' wrap the 'App' component element by 'BrowserRouter' element. The 'BrowserRouter' element loads from the 'react-router-dom' package.
src/index.js:
import React from "react"; import ReactDOM from "react-dom/client"; import "./index.css"; import App from "./App"; import "bootstrap/dist/css/bootstrap.min.css"; import { BrowserRouter } from "react-router-dom"; const root = ReactDOM.createRoot(document.getElementById("root")); root.render( <BrowserRouter> <App /> </BrowserRouter> );
Create A React Component 'Home':
Let's create a React component like 'Home' in 'pages' folder(new folder). The 'Home' component is a guest page, so both authentication and non-authenticated users can access the page.
src/pages/Home.js:
import Card from "react-bootstrap/Card"; const Home = () => { return ( <> <div className="d-flex justify-content-center align-items-center" style={{ minHeight: "500px", minWidth: "600px" }} > <Card> <Card.Body> <Card.Text className="text-center"> <b>Welcome! A Demo On ReactJS Authentication with JWT Token</b> </Card.Text> </Card.Body> </Card> </div> </> ); }; export default Home;Configure the 'Home' component route in 'App' component.
src/App.js:
import logo from "./logo.svg"; import "./App.css"; import Layout from "./components/shared/Layout"; import { Route, Routes } from "react-router-dom"; import Home from "./pages/Home"; function App() { return ( <> <Layout> <Routes> <Route path="/" element={<Home />}></Route> </Routes> </Layout> </> ); } export default App;
- (Line: 12) The home page route is configured to the 'Home' component.
Create A React Component 'Login':
Let's create a React component 'Login' in 'pages' folder.
src/pages/Login.js:
import { useRef } from "react"; import { Col, Container, Row } from "react-bootstrap"; import Button from "react-bootstrap/Button"; import Form from "react-bootstrap/Form"; const Login = () => { const userName = useRef(""); const password = useRef(""); const loginSubmit = async () => {}; return ( <> <Container className="mt-2"> <Row> <Col className="col-md-8 offset-md-2"> <legend>Login Form</legend> <form> <Form.Group className="mb-3" controlId="formUserName"> <Form.Label>User Name</Form.Label> <Form.Control type="text" ref={userName} /> </Form.Group> <Form.Group className="mb-3" controlId="formPassword"> <Form.Label>Password</Form.Label> <Form.Control type="password" ref={password} /> </Form.Group> <Button variant="primary" type="button" onClick={loginSubmit}> Login </Button> </form> </Col> </Row> </Container> </> ); }; export default Login;
- Here we added the React Bootstrap added the Login form.
src/App.js:
import logo from "./logo.svg"; import "./App.css"; import Layout from "./components/shared/Layout"; import { Route, Routes } from "react-router-dom"; import Home from "./pages/Home"; import Login from "./pages/Login"; function App() { return ( <> <Layout> <Routes> <Route path="/" element={<Home />}></Route> <Route path="/login" element={<Login />}></Route> </Routes> </Layout> </> ); } export default App;Now add the 'Login' route menu item in the 'Layout' component.
src/components/shared/Layout.js:
import Navbar from "react-bootstrap/Navbar"; import { Container } from "react-bootstrap"; import Nav from "react-bootstrap/Nav"; import { Link } from "react-router-dom"; const Layout = ({ children }) => { return ( <> <Navbar bg="primary" variant="dark"> <Navbar.Brand> <Nav.Link as={Link} to="/"> Auth Demo </Nav.Link> </Navbar.Brand> <Navbar.Toggle aria-controls="responsive-navbar-nav" /> <Navbar.Collapse id="responsive-navbar-nav"> <Nav className="ms-auto"> <Nav.Link as={Link} to="/login"> Login </Nav.Link> </Nav> </Navbar.Collapse> </Navbar> <Container>{children}</Container> </> ); }; export default Layout;
- (Line: 17-19) Configure our '/login' route.
JWT Authentication API:
A Mock JWT API was developed in 'NestJS' which is a NodeJS framework. Check for usage description in Github
Install JWT Decode Library:
For to decode the access token we need to install the JWT Decode library.
npm i jwt-decode
Install Axios Library:
To invoke API calls let's install the 'axios' library.
npm i axios
Use ReactJS Context API To Store Authentication Information:
Authentication information has to be available to the entire ReactJS application, so we have to store it in some kind of store. For this demo, I'm going to store the authentication information with the help of ReactJs Context API. Let's create a file like 'AuthContext.js' inside of the 'components/shared' folders.
src/components/shared/AuthContext.js:
import axios from "axios"; import { createContext, useState } from "react"; import jwt_decode from "jwt-decode"; import { useNavigate } from "react-router-dom"; const AuthContext = createContext(); export const AuthContextProvider = ({ children }) => { const [user, setUser] = useState(() => { if (localStorage.getItem("tokens")) { let tokens = JSON.parse(localStorage.getItem("tokens")); return jwt_decode(tokens.access_token); } return null; }); const navigate = useNavigate(); const login = async (payload) => { const apiResponse = await axios.post( "http://localhost:4000/auth/login", payload ); localStorage.setItem("tokens", JSON.stringify(apiResponse.data)); setUser(jwt_decode(apiResponse.data.access_token)); navigate("/"); }; return ( <AuthContext.Provider value={{ user, login }}> {children} </AuthContext.Provider> ); }; export default AuthContext;
- (Line: 6) The 'createContext' assigned to the 'AuthContex' variable. The 'createContex' loads from the 'react' library.
- (Line: 8) Create our component for API context like 'AuthContextProvider'.
- (Line: 9-15) Authenticated user information will be stored in the 'user' state variable. For the initial value, we are checking our browser local storage variable if a token exists then decrypt those values and then assign them to the 'user' variable.
- (Line: 17) Initialized use navigation variable.
- (Line: 19-27) Our login API call. Here are response tokens saving to browser local storage. Assigning the decrypted access token values to 'userVaraible' and then finally navigating to the home page.
- (Line: 29-31) The 'AuthContext.Provider' element receives input like 'user' property and 'login' method. So these input values are now available to our entire ReactJS application.
src/App.js:
import "./App.css"; import Layout from "./components/shared/Layout"; import { Route, Routes } from "react-router-dom"; import Home from "./pages/Home"; import Login from "./pages/Login"; import { AuthContextProvider } from "./components/shared/AuthContext"; function App() { return ( <> <AuthContextProvider> <Layout> <Routes> <Route path="/" element={<Home />}></Route> <Route path="/login" element={<Login />}></Route> </Routes> </Layout> </AuthContextProvider> </> ); } export default App;
Use 'AuthContext' In Login Component:
Let's use the 'AuthContext' in our 'Login' component so that we can invoke the 'login' method in 'AuthContextProvider' component.
src/pages/Login.js:
import { useContext, useRef } from "react"; import { Col, Container, Row } from "react-bootstrap"; import Button from "react-bootstrap/Button"; import Form from "react-bootstrap/Form"; import AuthContext from "../components/shared/AuthContext"; const Login = () => { const userName = useRef(""); const password = useRef(""); const {login}= useContext(AuthContext) const loginSubmit = async () => { let payload = { username: userName.current.value, password: password.current.value } await login(payload); }; return ( <> <Container className="mt-2"> <Row> <Col className="col-md-8 offset-md-2"> <legend>Login Form</legend> <form> <Form.Group className="mb-3" controlId="formUserName"> <Form.Label>User Name</Form.Label> <Form.Control type="text" ref={userName} /> </Form.Group> <Form.Group className="mb-3" controlId="formPassword"> <Form.Label>Password</Form.Label> <Form.Control type="password" ref={password} /> </Form.Group> <Button variant="primary" type="button" onClick={loginSubmit}> Login </Button> </form> </Col> </Row> </Container> </> ); }; export default Login;
- (Line: 9) Using 'useContext' service we initialized the 'AuthContext' instance and reading the 'login' method reference.
- (Line: 12-15) Preparing our login form payload.
- (Line: 16) Invoking our Login API.
Display Menu Items Based On User Authentication:
Let's implement our logic to display menu items based on user authentication in 'Layout.js' component.
src/components/shared/Layout.js:
import Navbar from "react-bootstrap/Navbar"; import { Container } from "react-bootstrap"; import Nav from "react-bootstrap/Nav"; import { Link } from "react-router-dom"; import { useContext } from "react"; import AuthContext from "./AuthContext"; const Layout = ({ children }) => { const { user } = useContext(AuthContext); return ( <> <Navbar bg="primary" variant="dark"> <Navbar.Brand> <Nav.Link as={Link} to="/"> Auth Demo </Nav.Link> </Navbar.Brand> <Navbar.Toggle aria-controls="responsive-navbar-nav" /> <Navbar.Collapse id="responsive-navbar-nav"> <Nav className="ms-auto"> {!user && ( <Nav.Link as={Link} to="/login"> Login </Nav.Link> )} {user && <Nav.Link href="#">{user?.email}</Nav.Link>} </Nav> </Navbar.Collapse> </Navbar> <Container>{children}</Container> </> ); }; export default Layout;
- (Line :8) Using 'useContext' initialized the 'AuthContext' and then reading the 'user' property.
- (Line: 20-24) The 'user' variable empty means not authenticated then show 'Login' menu item
- (Line: 25) The 'user' variable contains authenticated user information and then displays the user email.
(Step 2):
(Step 3)
Create ReactJS Component 'FavouriteMovie':
Let's create a new ReactJS component like 'FavouriteMovie'.
src/pages/FavouriteMovie.js:
const FavouriteMovie = () => { return <></>; }; export default FavouriteMovie;Configure route for the 'FavouriteMovie' component in the 'App' component.
src/App.js:
import "./App.css"; import Layout from "./components/shared/Layout"; import { Route, Routes } from "react-router-dom"; import Home from "./pages/Home"; import Login from "./pages/Login"; import { AuthContextProvider } from "./components/shared/AuthContext"; import FavouriteMovie from "./pages/FavouriteMovie"; function App() { return ( <> <AuthContextProvider> <Layout> <Routes> <Route path="/" element={<Home />}></Route> <Route path="/login" element={<Login />}></Route> <Route path="/fav-movies" element={<FavouriteMovie />}></Route> </Routes> </Layout> </AuthContextProvider> </> ); } export default App;Let's add the menu item for the 'FavouriteMovie' component in the 'Layout' component.
src/components/shared/Layout.js:
import Navbar from "react-bootstrap/Navbar"; import { Container } from "react-bootstrap"; import Nav from "react-bootstrap/Nav"; import { Link } from "react-router-dom"; import { useContext } from "react"; import AuthContext from "./AuthContext"; const Layout = ({ children }) => { const { user } = useContext(AuthContext); return ( <> <Navbar bg="primary" variant="dark"> <Navbar.Brand> <Nav.Link as={Link} to="/"> Auth Demo </Nav.Link> </Navbar.Brand> <Navbar.Toggle aria-controls="responsive-navbar-nav" /> <Navbar.Collapse id="responsive-navbar-nav"> <Nav> {user && ( <Nav.Link as={Link} to="/fav-movies"> Favourite Movie </Nav.Link> )} </Nav> <Nav className="ms-auto"> {!user && ( <Nav.Link as={Link} to="/login"> Login </Nav.Link> )} {user && <Nav.Link href="#">{user?.email}</Nav.Link>} </Nav> </Navbar.Collapse> </Navbar> <Container>{children}</Container> </> ); }; export default Layout;
- (Line: 20-24) The 'FavouriteMovies' menu item only displays for authenticated users.
Interceptor To Configure Authorization Header For API Request:
Using Axios we can implement an interceptor to auto-configure the authorization header that uses the access token as a value for the request. So let's create a file like 'jwtInterceptor.js' in the 'components/shared/' folder.
src/components/shared/jwtInterceptor.js:
import axios from "axios"; const jwtInterceoptor = axios.create({}); jwtInterceoptor.interceptors.request.use((config) => { let tokensData = JSON.parse(localStorage.getItem("tokens")); config.headers.common["Authorization"] = `bearer ${tokensData.access_token}`; return config; }); export default jwtInterceoptor;
- (Line: 3) Creating an instance of 'Axios' and assigned to 'jwtInterceptor' variable.
- (Line: 5) The 'jwtInterceptor.interceptor.request.use()' method gets executed on invoking any API call using 'jwtInterceptor' instance.
- (Line: 6) Fetching access token and refresh token values from the browser local storage.
- (Line: 7) Add the 'Authorization' header and its value like the 'bearer' space separated access token. value.
'FavouriteMovie' Component Consume Secured API Endpoint:
In the 'FavourieMovie' component let's try to consume the secured API Endpoint. So to consume the secured API we have to pass our access token as an Authorization header value.
src/pages/FavouriteMovie.js:
import { useState, useEffect } from "react"; import Card from "react-bootstrap/Card"; import Col from "react-bootstrap/Col"; import Row from "react-bootstrap/Row"; import jwtInterceptor from "../components/shared/jwtInterceptor"; const FavouriteMovie = () => { const [movies, setMovies] = useState([]); useEffect(() => { jwtInterceptor .get("http://localhost:4000/user/fav-movies") .then((response) => { setMovies(response.data); }); }, []); return ( <> <Row xs={1} md={2} className="g-4"> {movies.map((movie) => ( <Col key={movie.id}> <Card> <Card.Body> <Card.Title>{movie.name}</Card.Title> <Card.Text>Genre: {movie.genre}</Card.Text> </Card.Body> </Card> </Col> ))} </Row> </> ); }; export default FavouriteMovie;
- (Line: 7) The 'movies' is our state variable that holds the response of our secured API.
- (Line: 9-15) Invoking our secured API. Here we use 'jwtInterceptor' which automatically adds an authorization header with an access token as its value.
- (Line: 29-30) Binding our API response data.
(Step 2)
Refresh Token:
The 'Access Token' is a short-lived token, when it expired we renew it using the 'RefreshToken'.
Let's extend our interceptor to invoke the refresh token endpoint automatically whenever the access token expires.
src/component/shared/jwtInterceptor.js:
import axios from "axios"; const jwtInterceoptor = axios.create({}); jwtInterceoptor.interceptors.request.use((config) => { let tokensData = JSON.parse(localStorage.getItem("tokens")); config.headers.common["Authorization"] = `bearer ${tokensData.access_token}`; return config; }); jwtInterceoptor.interceptors.response.use( (response) => { return response; }, async (error) => { if (error.response.status === 401) { const authData = JSON.parse(localStorage.getItem("tokens")); const payload = { access_token: authData.access_token, refresh_token: authData.refreshToken, }; let apiResponse = await axios.post( "http://localhost:4000/auth/refreshtoken", payload ); localStorage.setItem("tokens", JSON.stringify(apiResponse.data)); error.config.headers[ "Authorization" ] = `bearer ${apiResponse.data.access_token}`; return axios(error.config); } else { return Promise.reject(error); } } ); export default jwtInterceoptor;
- (Line: 11) The 'jwtInterceptor.interceptors.response.use()' executes on receiving the API response.
- (Line: 12-14) If API returns a successful response then normal flow continues to execute
- (Line: 15-35) If API fails then this method gets executed.
- (Line: 16) Checking API fails due to an unauthorized exception(status code 401). So this unauthorized error when our access token expires or is invalid.
- (Line: 17) Fetching our access token and refresh token from the browser's local storage.
- (Line: 18-21) Preparing a payload for refresh token API
- (Line: 23-26) Invoking the refresh token API.
- (Line: 27) Updating the access token and refresh token values in browser local storage.
- (Line: 28-30) Adding our new access token value as an authorization header
- (Line: 31) Invoking the actual API call which is failed due to the expiration of the access token
Implement Protected Routes:
Now either authenticated users or non-authenticated users can access any route in our application. So we have to protect our routes like authenticated users can't access pages like 'login', similarly, non-authenticated users can't access the 'fav-movies' page.
Let's create a react component like 'ProtectedRoute' in the 'components/shared' folders.
src/component/shared/ProtectedRoute.js:
import { useContext } from "react"; import { Navigate } from "react-router-dom"; import AuthContext from "./AuthContext"; const ProtectedRoute = ({ children, accessBy }) => { const { user } = useContext(AuthContext); if (accessBy == "non-authenticated") { if (!user) { return children; } } else if (accessBy === "authenticated") { if (user) { return children; } } return <Navigate to="/"></Navigate>; }; export default ProtectedRoute;
- (Line: 6)The 'ProtectedRoute' component destructured props like 'children'(actual component to render for route), 'accessBy'(a custom configuration whether the route can be accessed by either authenticated or non-authenticated user).
- (Line: 7) Fetching the 'user' information form the 'AuthContext'.
- (Line: 9-12) If the 'accessBy' value is 'non-authenticated' and the user is not logged into our application then the user can access the page of the route.
- (Line: 13-17) If the 'accessBy' value is 'authenticated' and the user is logged into our application then the user can access the page of the route.
- (Line: 19) By default home page can be accessed by any kind of user we are redirected to the home page using the 'Navigate' component by specifying the route to redirect.
src/App.js:
import "./App.css"; import Layout from "./components/shared/Layout"; import { Route, Routes } from "react-router-dom"; import Home from "./pages/Home"; import Login from "./pages/Login"; import { AuthContextProvider } from "./components/shared/AuthContext"; import FavouriteMovie from "./pages/FavouriteMovie"; import ProtectedRoute from "./components/shared/ProtectedRoute"; function App() { return ( <> <AuthContextProvider> <Layout> <Routes> <Route path="/" element={<Home />}></Route> <Route path="/login" element={ <ProtectedRoute accessBy="non-authenticated"> <Login /> </ProtectedRoute> } ></Route> <Route path="/fav-movies" element={ <ProtectedRoute accessBy=""> <FavouriteMovie /> </ProtectedRoute> } ></Route> </Routes> </Layout> </AuthContextProvider> </> ); } export default App;
Implement Logout:
Let's implement our logout logic in the 'AuthContextProvider' component.
src/components/shared/AuthContext.js:
import axios from "axios"; import { createContext, useState } from "react"; import jwt_decode from "jwt-decode"; import { useNavigate } from "react-router-dom"; const AuthContext = createContext(); export const AuthContextProvider = ({ children }) => { const [user, setUser] = useState(() => { if (localStorage.getItem("tokens")) { let tokens = JSON.parse(localStorage.getItem("tokens")); return jwt_decode(tokens.access_token); } return null; }); const navigate = useNavigate(); const login = async (payload) => { const apiResponse = await axios.post( "http://localhost:4000/auth/login", payload ); localStorage.setItem("tokens", JSON.stringify(apiResponse.data)); setUser(jwt_decode(apiResponse.data.access_token)); navigate("/"); }; const logout = async () => { // invoke the logout API call, for our NestJS API no logout API localStorage.removeItem("tokens"); setUser(null); navigate("/"); }; return ( <AuthContext.Provider value={{ user, login, logout }}> {children} </AuthContext.Provider> ); }; export default AuthContext;
- (Line: 28-34) For logout, we have to remove our token data from the browser's local storage and we have to reset our 'user' variable to 'null'
- (Line: 36) The 'logout' method exposing from our 'AuthContext.Provider'.
src/components/shared/Layout.js:
import Navbar from "react-bootstrap/Navbar"; import { Container, Button } from "react-bootstrap"; import Nav from "react-bootstrap/Nav"; import { Link } from "react-router-dom"; import { useContext } from "react"; import AuthContext from "./AuthContext"; const Layout = ({ children }) => { const { user, logout } = useContext(AuthContext); return ( <> <Navbar bg="primary" variant="dark"> <Navbar.Brand> <Nav.Link as={Link} to="/"> Auth Demo </Nav.Link> </Navbar.Brand> <Navbar.Toggle aria-controls="responsive-navbar-nav" /> <Navbar.Collapse id="responsive-navbar-nav"> <Nav> {user && ( <Nav.Link as={Link} to="/fav-movies"> Favourite Movie </Nav.Link> )} </Nav> <Nav className="ms-auto"> {!user && ( <Nav.Link as={Link} to="/login"> Login </Nav.Link> )} {user && <Nav.Link href="#">{user?.email}</Nav.Link>} </Nav> {user && ( <Button variant="outline-success" type="button" onClick={() => { logout(); }} > Logout </Button> )} </Navbar.Collapse> </Navbar> <Container>{children}</Container> </> ); }; export default Layout;
- (Line: 8) Read the 'logout' method from the 'AuthContext'.
- (Line: 34-44) Add the 'Logout' button and its click invokes our 'logout' method.
Support Me!
Buy Me A Coffee
PayPal Me
Video Session:
Wrapping Up:
Hopefully, I think this article delivered some useful information on the ReactJS(v18) Authentication with JWT Access Token And Refresh Token. I love to have your feedback, suggestions, and better techniques in the comment section below.
Comments
Post a Comment