> For the complete documentation index, see [llms.txt](https://ztrust.gitbook.io/ztrust-documentation/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ztrust.gitbook.io/ztrust-documentation/user-manual-ztrust-v4.2/5.-securing-applications/5.7-securing-a-react-application.md).

# 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="/files/bBEKveGvTcaQaFeAbv9k" 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="/files/2mB5x0fqGpeMrQEVLFQ6" 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="/files/CCDKgzdn7vf4u7jdN668" 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="/files/3ctU4HR43AQWyjQQItSp" 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="/files/48JEUxwzefas9V03s6Sy" 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="/files/w2MtpuS6RcVoUOoR6Zun" 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="/files/X08ICDQfzeLrSpaaAdRi" 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="/files/HSxR4tXka228y7WBZRYZ" 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="/files/VZmEioY9rGEpQ1vwrMwl" 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="/files/zTMYD3Y57WAA3XqX3Ntw" 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<br>

  ```
  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`
