Skip to main content

ReactJS(v18) JWT Authentication Using HTTP Only Cookie

In this article, we will implement the ReactJS application authentication using the HTTP-only cookie.

HTTP Only Cookie:

In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing the 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 the authentication with HTTP-only JWT cookie then we no need to implement the 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 authenticate our client application with JWT HTTP-only cookie, I developed a NetJS(which is a node) Mock API.
Check the GitHub link and read the document on GitHub for how to use it.

By default the NestJS also runs under port number 3000, so we have to change to use another port number since our react application also runs 3000. So where to change you can find the GitHub readme document.

To avoid 'CORS' issue and to consume the API in our application our react js application URL need to be registered in the API project. So where to change you can find the GitHub readme document.

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";

Install React Router Package:

Install the react-router package
npm i react-router-dom

Add the 'BrowserRouter' element in the 'index.js'
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 'Layout':

Let's create a react component like 'Layout' inside of the 'components/shared' folders.
src/components/shared/Layout.js:
import { Container, Navbar } from "react-bootstrap";

const Layout = ({ children }) => {
  return (
    <>
      <Navbar bg="primary" variant="dark">
        <Navbar.Brand>JWT HTTP-Only Cookie</Navbar.Brand>
      </Navbar>
      <Container>{children}</Container>
    </>
  );
};
export default Layout;
  • Here we add the bootstrap 'Navbar'. All page-level components read as 'children' and are rendered here inside the container.
Add the 'Layout' component element in the 'App' component.
src/App.js:
import logo from "./logo.svg";
import "./App.css";
import Layout from "./components/shared/Layout";

function App() {
  return (
    <>
      <Layout></Layout>
    </>
  );
}
export default App;

Create A React Component 'Home':

Let's create a react component like 'Home' in 'pages' folder. The 'Home' component can be accessed by either authenticated or non-authenticated users just like the guest page.
src/pages/Home.js:
import { Card } from "react-bootstrap";

const Home = () => {
  return (
    <>
      <div
        className="d-flex justify-content-center align-items-center"
        style={{ minHeight: "500px", minWidth: "600px" }}
      >
        <Card>
          <Card.Body>
            <Card.Text>
              Welcome to demo on ReactJS (v18) Jwt Authentication with HTTP Only
              cookie
            </Card.Text>
          </Card.Body>
        </Card>
      </div>
    </>
  );
};
export default Home;
In the 'App' component add the route for the 'Home' 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;

Create A React Component 'Login':

Let's create the react component  'Login' in the 'pages' folder.
src/pages/Login.js:
import { useRef } from "react";
import { Button, Col, Container, Row, Form } from "react-bootstrap";

const Login = () => {
  const email = 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.Group className="mb-3" controlId="formBasicEmail">
              <Form.Label>Email address</Form.Label>
              <Form.Control type="email" ref={email} />
            </Form.Group>
            <Form.Group className="mb-3" controlId="formPasswor">
              <Form.Label>Password</Form.Label>
              <Form.Control type="password" ref={password} />
            </Form.Group>
            <Button variant="primary" type="button" onClick={loginSubmit}>
              Login
            </Button>
          </Col>
        </Row>
      </Container>
    </>
  );
};
export default Login;
  • (Line: 5-6) The 'useRef' variables 'email' & 'password' to read the data from the form.
In the 'App' component add the route for the 'Login' 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' menu item in the 'Layout' component.
src/components/shared/Layout.js:
import { Container, Navbar, Nav } from "react-bootstrap";
import { Link } from "react-router-dom";

const Layout = ({ children }) => {
  return (
    <>
      <Navbar bg="primary" variant="dark">
        <Navbar.Brand as={Link} to="/">
          JWT HTTP-Only Cookie
        </Navbar.Brand>
        <Nav className="ms-auto">
          <Nav.Link as={Link} to="/login">
            Login
          </Nav.Link>
        </Nav>
      </Navbar>
      <Container>{children}</Container>
    </>
  );
};

export default Layout;

Install Axios:

To invoke the API calls let's install the Axios library.
npm i axios

Use ReactJS ContextAPI To Store Authentiction 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 { useNavigate } from "react-router-dom";

const AuthContext = createContext();

export const AuthContextProvider = ({ children }) => {
  const [user, setUser] = useState(() => {
    let userProfle = localStorage.getItem("userProfile");
    if (userProfle) {
      return JSON.parse(userProfle);
    }
    return null;
  });
  const navigate = useNavigate();
  const login = async (payload) => {
    await axios.post("http://localhost:4000/auth/login", payload, {
      withCredentials: true,
    });
    let apiResponse = await axios.get("http://localhost:4000/user-profile", {
      withCredentials: true,
    });
    localStorage.setItem("userProfile", JSON.stringify(apiResponse.data));
    setUser(apiResponse.data);
    navigate("/");
  };
  return (
    <>
      <AuthContext.Provider value={{ user, login }}>
        {children}
      </AuthContext.Provider>
    </>
  );
};

export default AuthContext;
  • (Line: 5) The 'createContext' assigned to the 'AuthContex' variable. The 'createContex' loads from the 'react' library.
  • (Line: 7) Create our component for API context like 'AuthContextProvider'.
  • (Line: 8-14) The 'user' state variable holds the authenticated user information. For the initial value here we check for browser local storage, this case helps when the user reloads the page.
  • (Line: 15) Initialized the navigation variable.
  • (Line: 16-26) In 'logn' method we invoke 2 API calls like 'user login API call', 'user profile API call'. The 'login' API call for user authentication on the success of the login API sends us an HTTPonly cookie. The 'user profile' API call is a secured API call that gets the authenticated information. Here for every API call, we have to pass configuration to API call like 'withCredentials' with 'true' because our client application and API application runs under different ports or domains so to store the login cookie into the browser or attach the cookie for every secured API endpoint request we need those configurations. Here 'user profile' API response saves into the 'user'(state variable) and browser local storage.
  • (Line: 29-31) In the 'AuthContext.Provider' element, we configure the 'value' attribute to which we pass our 'login'(method), 'user'(variable) because these properties have to be accessed by any component in our application.
Now add our 'AuthContextProvider' element as a parent of all components in the '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";
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 the Login component to invoke the Login API.
src/page/Login.js:
import { useContext, useRef } from "react";
import { Button, Col, Container, Row, Form } from "react-bootstrap";
import AuthContext from "../components/shared/AuthContext";

const Login = () => {
  const email = useRef("");
  const password = useRef("");
  const { login } = useContext(AuthContext);

  const loginSubmit = async () => {
    let payload = {
      email: email.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.Group className="mb-3" controlId="formBasicEmail">
              <Form.Label>Email address</Form.Label>
              <Form.Control type="email" ref={email} />
            </Form.Group>
            <Form.Group className="mb-3" controlId="formPasswor">
              <Form.Label>Password</Form.Label>
              <Form.Control type="password" ref={password} />
            </Form.Group>
            <Button variant="primary" type="button" onClick={loginSubmit}>
              Login
            </Button>
          </Col>
        </Row>
      </Container>
    </>
  );
};
export default Login;
  • (Line: 9) The 'useContext' loads from the 'react' library. So we pass our 'AuthContext' as input to the 'useContext' then it can expose the 'login' method reference.
  • (Line: 10-16) Prepare the payload for login API and then invoke the login API call.
Let's implement our logic to display menu items based on user authentication in 'Layout.js' component.
src/components/shared/Layout.js:
import { useContext } from "react";
import { Container, Navbar, Nav } from "react-bootstrap";
import { Link } from "react-router-dom";
import AuthContext from "./AuthContext";

const Layout = ({ children }) => {
  const { user } = useContext(AuthContext);
  return (
    <>
      <Navbar bg="primary" variant="dark">
        <Navbar.Brand as={Link} to="/">
          JWT HTTP-Only Cookie
        </Navbar.Brand>
        <Nav className="ms-auto">
          {user && <Nav.Link>{user?.email}</Nav.Link>}
          {!user && (
            <Nav.Link as={Link} to="/login">
              Login
            </Nav.Link>
          )}
        </Nav>
      </Navbar>
      <Container>{children}</Container>
    </>
  );
};

export default Layout;
  • (Line: 7) Read the 'user' information from the 'AuthContext'.
  • (Line: 15) Display authenticated user email address.
  • (Line: 16-20) Show the login menu item if the user is not authenticated.
(Step 1)
(Step 2)
(Step 3)

Create Rect Component 'Movies':

Let's create a React component like 'Movies' in the 'pages' folder.
src/pages/Movies.js:
const Movies = () => {
  return <></>;
};

export default Movies;
In the 'App' component add the route for the 'Movies' 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";
import { AuthContextProvider } from "./components/shared/AuthContext";
import Movies from "./Pages/Movies";

function App() {
  return (
    <>
      <AuthContextProvider>
        <Layout>
          <Routes>
            <Route path="/" element={<Home />}></Route>
            <Route path="/login" element={<Login />}></Route>
            <Route path="/movies" element={<Movies />}></Route>
          </Routes>
        </Layout>
      </AuthContextProvider>
    </>
  );
}
export default App;
In the 'Layout' component add the menu item for 'Movies' component.
src/components/sharedLayout.js:
import { useContext } from "react";
import { Container, Navbar, Nav } from "react-bootstrap";
import { Link } from "react-router-dom";
import AuthContext from "./AuthContext";

const Layout = ({ children }) => {
  const { user } = useContext(AuthContext);
  return (
    <>
      <Navbar bg="primary" variant="dark">
        <Navbar.Brand as={Link} to="/">
          JWT HTTP-Only Cookie
        </Navbar.Brand>
        <Nav>
          {user && (
            <Nav.Link as={Link} to="/movies">
              Movies
            </Nav.Link>
          )}
        </Nav>
        <Nav className="ms-auto">
          {user && <Nav.Link>{user?.email}</Nav.Link>}
          {!user && (
            <Nav.Link as={Link} to="/login">
              Login
            </Nav.Link>
          )}
        </Nav>
      </Navbar>
      <Container>{children}</Container>
    </>
  );
};

export default Layout;

The 'Movies' Component Consume A Secured Endpoint:

Let's consume a secured API like 'liked-movies' from the 'Movies' component.
src/pages/Movies.js:
import axios from "axios";
import { useEffect, useState } from "react";
import Card from "react-bootstrap/Card";
import ListGroup from "react-bootstrap/ListGroup";

const Movies = () => {
  const [movies, setMovies] = useState([]);

  useEffect(() => {
    axios
      .get("http://localhost:4000/liked-movies", { withCredentials: true })
      .then((response) => {
        setMovies(response.data);
      });
  }, []);
  return (
    <>
      <div
        className="d-flex justify-content-center align-items-center"
        style={{ minHeight: "500px", minWidth: "600px" }}
      >
        <Card>
          <Card.Header>Liked Movies</Card.Header>
          <ListGroup variant="flush">
            {movies.map((item) => (
              <ListGroup.Item>{item}</ListGroup.Item>
            ))}
          </ListGroup>
        </Card>
      </div>
    </>
  );
};

export default Movies;
  • (Line: 7) The 'useState' variable 'movies' to hold the API response.
  • (Line: 9-15) Invoking the secured API.

Axios Interceptor To Invoke The Refresh Token Endpoint:

The JWT access token is a short-lived access token, on its expiration we have to invoke the refresh token endpoint so that it regenerates a new JWT access token and updates it into our HTTP-Only auth cookie.

Here we are going to write an Axios interceptor for invoking the refresh token API call. So let's create a file like the 'jwtInterceptor.js' file in the 'helpers' folder (new folder).
src/helpers/jwtInterceptor.js:
import axios from "axios";

const jwtInterceptor = axios.create({});

jwtInterceptor.interceptors.response.use(
  (response) => {
    return response;
  },
  async (error) => {
    if (error.response.status === 401) {
      await axios
        .get("http://localhost:4000/refresh-token", {
          withCredentials: true,
        })
        .catch((err) => {
          return Promise.reject(err);
        });
      console.log(error.config);
      return axios(error.config);
    } else {
      return Promise.reject(error);
    }
  }
);

export default jwtInterceptor;
  • (Line: 3) Using 'axios.create({})' creating an instance of Axios and assign to the 'jwtInterceoptor' variable. Now 'jwtIntercoptor' is also an Axios that can be used to invoke the API calls.
  • (Line: 5) Here configuring the 'interceptor' for the 'jwtInterceptor' variable for a response. That means this interceptor gets executed after API returns a response(either a success or an error response).
  • (Line: 6-8) This method gets executed for success API response. Here we won't change any API flow.
  • (Line: 9) This method gets executed for error API response.
  • (Line: 10-20) If the error status is '401' that means unauthorized. then we are going to invoke the refresh token endpoint.
  • (Line: 11-17) Invoking the refresh token endpoint.
  • (Line: 19) Re-invoking the original API that 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 'movies' page.

Let's create a react component like 'ProtectedRoute' in the 'components/shared' folders.
src/components/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: 5)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: 6) Fetching the 'user' information form the 'AuthContext'.
  • (Line: 8-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 Movies from "./Pages/Movies";
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="/movies"
              element={
                <ProtectedRoute accessBy="authenticated">
                  <Movies />
                </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 { useNavigate } from "react-router-dom";

const AuthContext = createContext();

export const AuthContextProvider = ({ children }) => {
  const [user, setUser] = useState(() => {
    let userProfle = localStorage.getItem("userProfile");
    if (userProfle) {
      return JSON.parse(userProfle);
    }
    return null;
  });
  const navigate = useNavigate();
  const login = async (payload) => {
    await axios.post("http://localhost:4000/auth/login", payload, {
      withCredentials: true,
    });
    let apiResponse = await axios.get("http://localhost:4000/user-profile", {
      withCredentials: true,
    });
    localStorage.setItem("userProfile", JSON.stringify(apiResponse.data));
    setUser(apiResponse.data);
    navigate("/");
  };

  const logout = async () => {
    await axios.get("http://localhost:4000/logout", { withCredentials: true });
    localStorage.removeItem("userProfile");
    setUser(null);
    navigate("/login");
  };

  return (
    <>
      <AuthContext.Provider value={{ user, login, logout }}>
        {children}
      </AuthContext.Provider>
    </>
  );
};

export default AuthContext;
  • (Line: 28-33) Invoking the 'Logout' API call. Then remove the user profile information from the browser's local storage. Then empty the 'user' state variable and then navigate to 'login' page.
  • (Line: 37) Expose our 'logout' method by registering the 'value' attribute of 'AuthContext.Provider'.
Add the 'Logout' button as a menu item in the 'Layout' component.
src/components/shared/Layout.js:
import { useContext } from "react";
import { Container, Navbar, Nav, Button } from "react-bootstrap";
import { Link } from "react-router-dom";
import AuthContext from "./AuthContext";

const Layout = ({ children }) => {
  const { user, logout } = useContext(AuthContext);
  return (
    <>
      <Navbar bg="primary" variant="dark">
        <Navbar.Brand as={Link} to="/">
          JWT HTTP-Only Cookie
        </Navbar.Brand>
        <Nav>
          {user && (
            <Nav.Link as={Link} to="/movies">
              Movies
            </Nav.Link>
          )}
        </Nav>
        <Nav className="ms-auto">
          {user && <Nav.Link>{user?.email}</Nav.Link>}
          {!user && (
            <Nav.Link as={Link} to="/login">
              Login
            </Nav.Link>
          )}
        </Nav>
        {user && (
          <Button variant="outline-success" type="button" onClick={() => {logout()}}>
            Logout
          </Button>
        )}
      </Navbar>
      <Container>{children}</Container>
    </>
  );
};

export default Layout;
  • (Line: 7) Access the 'logout' method reference from the 'AuthContext'.
  • (Line: 30-32) Registered the 'Logout' button with 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 using HTTP-Only Cookie. I love to have your feedback, suggestions, and better techniques in the comment section below.

Refer:

Follow Me:

Comments

  1. Just wondering why you need both the JWT and the auth cookie? If the auth cookie is supplied on every API call, the JWT shouldn't be needed

    ReplyDelete

Post a Comment

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