# 5.7 Securing a React Application

Securing **React** applications with **Ztrust** using oidc-client-ts involves configuring both Ztrust and the React application to leverage OpenID Connect (OIDC) for authentication and authorization.

**Prerequisites**

Before integrating your **React application** with ZTrust, ensure the following are in place:

* **ZTrust SSO** – A running ZTrust instance configured as your identity and access management provider.
* **React Application** – A React project already set up. Authentication will be handled using [`oidc-client-ts`](https://github.com/authts/oidc-client-ts), a library for managing OpenID Connect (OIDC) and OAuth2 authentication flows in browser-based apps.
* **Configured Realm and Client** – A realm and client created in ZTrust with OIDC enabled. The client settings (**Client ID, Secret, Redirect URIs**) will be required by your React app.

With these prerequisites, your application will be ready to establish a secure connection with **ZTrust using OpenID Connect**.

### Step 1: Set up ZTrust

1. Access ZTrust Admin Console:

   <figure><img src="https://1778922777-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3EUK5AUZv0UVaI5S0CTM%2Fuploads%2FhayKxawjntHCFL11QgIq%2Fimage.png?alt=media&#x26;token=90dbe72a-4aaa-4f20-84c8-c0f68651c7c0" alt=""><figcaption><p>Fig 5.7.a: Master realm welcome page</p></figcaption></figure>
2. Click on **Manage Realms** in the sidebar to view the list of realms available in your **ZTrust**.

   <figure><img src="https://1778922777-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3EUK5AUZv0UVaI5S0CTM%2Fuploads%2FphSRQxm2xzUW8AAJO5ZL%2Fimage.png?alt=media&#x26;token=2ddbc8d0-5332-46fa-b145-3db41e896ee8" alt=""><figcaption><p>Fig 5.7.b: List of avalible realms under manage realms</p></figcaption></figure>
3. From the list of realms, select the **realm** where you want to secure **React** applications.

   <figure><img src="https://1778922777-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3EUK5AUZv0UVaI5S0CTM%2Fuploads%2FJOAEWrpbe2Up2qxPQPBq%2Fimage.png?alt=media&#x26;token=32498368-f119-467d-acb0-3249b39f758b" alt=""><figcaption><p>Fig 5.7.c: Welcome to Demo realm</p></figcaption></figure>
4. From the left **sidebar**, navigate to the **Clients** section.

   <figure><img src="https://1778922777-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3EUK5AUZv0UVaI5S0CTM%2Fuploads%2FWxwsdtU9YVSJyfV00UJG%2Fimage.png?alt=media&#x26;token=eb09cea2-bce2-40cc-9236-8cf006f26231" alt="" width="144"><figcaption><p>Fig 5.7.d: Navigating to clients section in side bar</p></figcaption></figure>
5. You will see a list of **clients** (applications). Choose/ Create the **client** for which you want to secure React Application.

   <figure><img src="https://1778922777-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3EUK5AUZv0UVaI5S0CTM%2Fuploads%2Fk7YD6NSy7hzt3E1W5n9a%2Fimage.png?alt=media&#x26;token=f91e3a67-1735-4de9-9362-46b1de6e6852" alt=""><figcaption><p>Fig 5.7.e: List of available clients</p></figcaption></figure>
6. After select your client, it will take you to the settings page.

   <figure><img src="https://1778922777-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3EUK5AUZv0UVaI5S0CTM%2Fuploads%2FS1oxrQCokqkTzwdGMgAr%2Fimage.png?alt=media&#x26;token=bd9727a4-cb0a-4cfa-a005-cf63bc723458" alt=""><figcaption><p>Fig 5.7.f: Client settings page</p></figcaption></figure>
7. Enter your application’s **redirect URL** in the **Valid Redirect URIs** field.

   <figure><img src="https://1778922777-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3EUK5AUZv0UVaI5S0CTM%2Fuploads%2F20rxOII9PaSJ4xTzP0U6%2Fimage.png?alt=media&#x26;token=bc37cd64-d9d0-443a-a4b3-a65fc027ce3f" alt=""><figcaption><p>Fig 5.7.g: In client setting tab general settings fields</p></figcaption></figure>
8. Then under **Capability** config turn on **Client authentication** and save

   <figure><img src="https://1778922777-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3EUK5AUZv0UVaI5S0CTM%2Fuploads%2FwasMLVDgzka4rmN8KbvL%2Fimage.png?alt=media&#x26;token=b7c3b48f-311d-444d-9b71-712df5a46ec6" alt="" width="563"><figcaption><p>Fig 5.7.h: In client setting tab capability config options</p></figcaption></figure>
9. You will now see a new tab enabled, called **Credentials**.

   <figure><img src="https://1778922777-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3EUK5AUZv0UVaI5S0CTM%2Fuploads%2FtEPiR2OLkYNF924NVRLC%2Fimage.png?alt=media&#x26;token=2ce3deef-febc-44ff-969b-4f56f83f3b4c" alt="" width="563"><figcaption><p>Fig 5.7.i: Client settings tab</p></figcaption></figure>
10. Navigate to the **Credentials** tab, where you can view and copy the **Client Secret**.

    <figure><img src="https://1778922777-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3EUK5AUZv0UVaI5S0CTM%2Fuploads%2FINetenUEEInw9dKDoCQt%2Fimage.png?alt=media&#x26;token=6817eddc-7cd9-4cf1-8087-73fac846602f" alt="" width="563"><figcaption><p>Fig 5.7.j: Navigating to Credentials tab</p></figcaption></figure>
11. With the ZTrust configuration complete, we can now move on to the React Application side of the setup.

### Step 2. React Application Setup with oidc-client-ts

* **Install dependencies:**\
  \
  `npm install oidc-client-ts react-oidc-context react-router-dom`
* **Set up the OIDC configuration:**\
  Create an instance Create a configuration object with your Ztrust client details. Inside src/oidcConfig.js\\

  ```
  export const oidcConfig = {
   authority: "http://localhost:8080/realms/test",
   client_id: "app-client",
   redirect_uri: window.location.origin,
   response_type: "code",
   scope: "openid profile email",
   post_logout_redirect_uri: window.location.origin,
   onSigninCallback: () => window.history.replaceState({}, document.title, window.location.pathname),
  };

  ```
* **Wrap your app with the AuthProvider:**\
  Import the AuthProvider and your oidcConfig and wrap your root component in src/main.jsx (or main.tsx).

  ```
  import React from 'react';
  import ReactDOM from 'react-dom/client';
  import { AuthProvider } from 'react-oidc-context';
  import App from './App.jsx';
  import { oidcConfig } from './oidcConfig';


  ReactDOM.createRoot(document.getElementById('root')).render(
   <React.StrictMode>
     <AuthProvider {...oidcConfig}>
       <App />
     </AuthProvider>
   </React.StrictMode>
  );

  ```
* **Implement authentication logic and routing:**\
  The logic for handling authentication and routing within your components (e.g., using useAuth to get the authentication state and protecting routes with withAuthenticationRequired) is exactly the same as in a standard React application.

  ```

  import { useState } from 'react'
  import reactLogo from './assets/react.svg'
  import viteLogo from '/vite.svg'
  import './App.css'


  import { useAuth } from 'react-oidc-context';
  import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
  import SecurePage from './pages/SecurePage';
  import HomePage from './pages/HomePage';


  function App() {
   const auth = useAuth();


   return (
     <BrowserRouter>
       <nav>
         <Link to="/">Home</Link>
         <Link to="/secure">Secure Page</Link>
         {!auth.isAuthenticated && (
           <button onClick={() => auth.signinRedirect()}>Log in</button>
         )}
         {auth.isAuthenticated && (
           <button onClick={() => auth.signoutRedirect()}>Log out</button>
         )}
       </nav>
       <Routes>
         <Route path="/" element={<HomePage />} />
         <Route path="/secure" element={<SecurePage />} />
       </Routes>
     </BrowserRouter>
   );
  }


  export default App

  ```
* **Start your Vite dev server:**\
  `npm run dev`
