Skip to main content

ReactJS(v18) Authentication With JWT AccessToken And Refresh Token


In this article, we are going to do ReactJS(v18) application authentication using the JWT Access Token and Refresh Token.

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.
Render the 'Layout' component element in 'App.js' component.
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.
Configure the 'Login' 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";
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.
Now in 'App' component use 'AuthContextProvider' element as the parent element so that the 'AuthContext' data can be accessed by any component in our 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 1)

(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 1)

(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.
Now wrap our 'ProtectedRoute' component around the actual page components specified to the 'element' attribute of 'Route' in '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";
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'.
Now in the 'Layout' component add our 'Logout' button as a menu item.
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.

Refer:

Follow Me:

Comments

Popular posts from this blog

.NET6 Web API CRUD Operation With Entity Framework Core

In this article, we are going to do a small demo on AspNetCore 6 Web API CRUD operations. What Is Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains a programming function that can be requested via HTTP calls to save or fetch the data for their respective clients. Some of the key characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build REST full services. Create A .NET6 Web API Application: Let's create a .Net6 Web API sample application to accomplish our

A Small Guide On NestJS Queues

NestJS Application Queues helps to deal with application scaling and performance challenges. When To Use Queues?: API request that mostly involves in time taking operations like CPU bound operation, doing them synchronously which will result in thread blocking. So to avoid these issues, it is an appropriate way to make the CPU-bound operation separate background job.  In nestjs one of the best solutions for these kinds of tasks is to implement the Queues. For queueing mechanism in the nestjs application most recommended library is '@nestjs/bull'(Bull is nodejs queue library). The 'Bull' depends on Redis cache for data storage like a job. So in this queueing technique, we will create services like 'Producer' and 'Consumer'. The 'Producer' is used to push our jobs into the Redis stores. The consumer will read those jobs(eg: CPU Bound Operations) and process them. So by using this queues technique user requests processed very fastly because actually

Part-1 Angular JWT Authentication Using HTTP Only Cookie[Angular V13]

In this article, we are going to implement a sample angular application authentication using HTTP only cookie that contains a JWT token. HTTP Only JWT Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-Only cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use authentication with HTTP only JWT cookie then we no need to implement custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To implement JWT cookie authentication we need to set up an API. For that, I had created a mock authentication API(Using the NestJS Se

Usage Of CancellationToken In Asp.Net Core Applications

When To Use CancellationToken?: In a web application request abortion or orphan, requests are quite common. On users disconnected by network interruption or navigating between multiple pages before proper response or closing of the browser, tabs make the request aborted or orphan. An orphan request can't deliver a response to the client, but it will execute all steps(like database calls, HTTP calls, etc) at the server. Complete execution of an orphan request at the server might not be a problem generally if at all requests need to work on time taking a job at the server in those cases might be nice to terminate the execution immediately. So CancellationToken can be used to terminate a request execution at the server immediately once the request is aborted or orphan. Here we are going to see some sample code snippets about implementing a CancellationToken for Entity FrameworkCore, Dapper ORM, and HttpClient calls in Asp.NetCore MVC application. Note: The sample codes I will show in

Unit Testing Asp.NetCore Web API Using xUnit[.NET6]

In this article, we are going to write test cases to an Asp.NetCore Web API(.NET6) application using the xUnit. xUnit For .NET: The xUnit for .Net is a free, open-source, community-focused unit testing tool for .NET applications. By default .Net also provides a xUnit project template to implement test cases. Unit test cases build upon the 'AAA' formula that means 'Arrange', 'Act' and 'Assert' Arrange - Declaring variables, objects, instantiating mocks, etc. Act - Calling or invoking the method that needs to be tested. Assert - The assert ensures that code behaves as expected means yielding expected output. Create An API And Unit Test Projects: Let's create a .Net6 Web API and xUnit sample applications to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. Create a fo

Blazor WebAssembly Custom Authentication From Scratch

In this article, we are going to explore and implement custom authentication from the scratch. In this sample, we will use JWT authentication for user authentication. Main Building Blocks Of Blazor WebAssembly Authentication: The core concepts of blazor webassembly authentication are: AuthenticationStateProvider Service AuthorizeView Component Task<AuthenticationState> Cascading Property CascadingAuthenticationState Component AuthorizeRouteView Component AuthenticationStateProvider Service - this provider holds the authentication information about the login user. The 'GetAuthenticationStateAsync()' method in the Authentication state provider returns user AuthenticationState. The 'NotifyAuthenticationStateChaged()' to notify the latest user information within the components which using this AuthenticationStateProvider. AuthorizeView Component - displays different content depending on the user authorization state. This component uses the AuthenticationStateProvider

Angular 14 Reactive Forms Example

In this article, we will explore the Angular(14) reactive forms with an example. Reactive Forms: Angular reactive forms support model-driven techniques to handle the form's input values. The reactive forms state is immutable, any form filed change creates a new state for the form. Reactive forms are built around observable streams, where form inputs and values are provided as streams of input values, which can be accessed synchronously. Some key notations that involve in reactive forms are like: FormControl - each input element in the form is 'FormControl'. The 'FormControl' tracks the value and validation status of form fields. FormGroup - Track the value and validate the state of the group of 'FormControl'. FormBuilder - Angular service which can be used to create the 'FormGroup' or FormControl instance quickly. Form Array - That can hold infinite form control, this helps to create dynamic forms. Create An Angular(14) Application: Let'

How Response Caching Works In Asp.Net Core

What Is Response Caching?: Response Caching means storing of response output and using stored response until it's under it's the expiration time. Response Caching approach cuts down some requests to the server and also reduces some workload on the server. Response Caching Headers: Response Caching carried out by the few Http based headers information between client and server. Main Response Caching Headers are like below Cache-Control Pragma Vary Cache-Control Header: Cache-Control header is the main header type for the response caching. Cache-Control will be decorated with the following directives. public - this directive indicates any cache may store the response. private - this directive allows to store response with respect to a single user and can't be stored with shared cache stores. max-age - this directive represents a time to hold a response in the cache. no-cache - this directive represents no storing of response and always fetch the fr

Different HttpClient Techniques To Consume API Calls In Minimal API[.NET6]

In this article, we are going to implement different HttpClient techniques to consume API calls in minimal API. The different HttpClient techniques that we are going to explore are like: Register HttpClient Object Explicitly In DI(Dependency Injection Service) Named Client Type Client HttpRequestMessage Object Create A .NET6 Minimal API Project: Let's create a .Net6 Minimal API sample project to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. CLI command For Minimal API Project dotnet new webapi -minimal -o Your_Project_Name Create A Third Party API Response Model: Here I'm going to use a free third-party rest API that is "https://jsonplaceholder.typicode.com/posts". So to receive the response let's create a response model like 'Post.cs'. Program.cs:(Add Post.cs c

.Net5 Web API Managing Files Using Azure Blob Storage

In this article, we are going to understand the different file operations like uploading, reading, downloading, and deleting in .Net5 Web API application using Azure Blob Storage. Azure Blob Storage: Azure blob storage is Microsoft cloud storage. Blob storage can store a massive amount of file data as unstructured data. The unstructured data means not belong to any specific type, which means text or binary data. So something like images or pdf or videos to store in the cloud, then the most recommended is to use the blob store. The key component to creating azure blob storage resource: Storage Account:- A Storage account gives a unique namespace in Azure for all the data we will save. Every object that we store in Azure Storage has an address. The address is nothing but the unique name of our Storage Account name. The combination of the account name and the Azure Storage blob endpoint forms the base address for each object in our Storage account. For example, if our Storage Account is n