<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Prem on Medium]]></title>
        <description><![CDATA[Stories by Prem on Medium]]></description>
        <link>https://medium.com/@prem6271?source=rss-75ffd55f3f0f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YL3dkq4nuWkziVaWdFvWMQ.jpeg</url>
            <title>Stories by Prem on Medium</title>
            <link>https://medium.com/@prem6271?source=rss-75ffd55f3f0f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 17 May 2026 19:21:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prem6271/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Integrate Okta with ReactJS and NodeJS]]></title>
            <link>https://medium.com/@prem6271/integrate-okta-with-reactjs-nodejs-356d35f7984?source=rss-75ffd55f3f0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/356d35f7984</guid>
            <dc:creator><![CDATA[Prem]]></dc:creator>
            <pubDate>Thu, 10 Aug 2023 09:48:16 GMT</pubDate>
            <atom:updated>2023-08-10T10:20:04.367Z</atom:updated>
            <content:encoded><![CDATA[<h3>Integrate Okta with ReactJS + NodeJS</h3><h3><strong>Introduction</strong></h3><p>Any web application needs an authentication layer. Either you can build one yourself or integrate with a managed service like Okta.</p><p>What is Okta ? As defined in their blogs, Okta connects any person with any application on any device. It is an enterprise-grade, identity management service, built for the cloud, but compatible with many on-premises applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*GFcOgkeVRFtrnzQaDkCk4g.png" /></figure><h3>Prerequisites</h3><p>Before we dive into the integration process, make sure you have the following prerequisites:</p><ul><li><strong>Node.js</strong>: Ensure you have Node.js installed on your development machine. You can download it from the official website.</li><li><strong>React Application</strong>: Have a React application set up. You can use Create React App or any other React boilerplate.</li><li><strong>Node.js Backend</strong>: Set up a basic Node.js backend for your application. This backend will handle communication with Okta and user authentication.</li></ul><h3>Integration Steps for React</h3><h4>Step 1: Create an Okta SPA Application</h4><ul><li>Visit <a href="https://developer.okta.com/">https://developer.okta.com/</a> and create an account if you don’t have one already.</li><li>Navigate to “Applications” and click “Create App Integration”</li><li>Choose sign-in method as “OIDC” and choose “Single-Page App” as the application type.</li><li>Configure the application settings. Check Grant type “Authorization Code” and configure the Sign-In and Sign-Out redirect URIs. If your react app is running on port 3000, then modify the sign-in and sign-out URLs accordingly. You can add URLs for all environments (one for localhost development, one for your staging env, etc..)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hOYXIHCffyuPco98CfpKxw.png" /></figure><p>Once your app is created, note down the client-id (looks something like 0oaabe9nztqcDQiEC5d7) and domain name (can be fetched from your okta url e.g. if your url is dev-98112532-admin.okta.com, then your domain name is dev-98112532.okta.com i.e. without the admin)</p><h4>Step 2: Setup React Application</h4><ul><li>Install the Okta React dependencies</li></ul><pre>npm install @okta/okta-react @okta/okta-auth-js</pre><ul><li>In your src folder, create a file called oktaConfig.js with following content. Replace clientId, redirectUri, issuer as per your okta app setting.</li><li>Scope defines the information that you would like to pass on in your accessToken</li></ul><pre>export const oktaConfig = {<br>    clientId: `your-client-id`,<br>    issuer: `https://your-okta-domain/oauth2/default`,<br>    redirectUri: `http://localhost:3000/login/callback`, // this makes it so redirects to login if not logged in for secure routes<br>    scopes: [&quot;openid&quot;, &quot;profile&quot;, &quot;email&quot;],<br>    pkce: true,<br>    disableHttpsCheck: true,<br>}; </pre><ul><li>Import the oktaConfig.js into your App.jsx. Below is the sample code.</li></ul><pre>import React from &#39;react&#39;<br>import { Route, Routes, useNavigate } from &#39;react-router-dom&#39;;<br><br>import store from &#39;./store&#39;;<br>import { Provider } from &#39;react-redux&#39;;<br><br>import Authenticated from &#39;./components/Authenticated&#39;;<br>import { Security, LoginCallback } from &quot;@okta/okta-react&quot;;<br>import { OktaAuth, toRelativeUrl } from &quot;@okta/okta-auth-js&quot;;<br>import { oktaConfig } from &quot;./oktaConfig&quot;;<br>const oktaAuth = new OktaAuth(oktaConfig);<br><br>const App = () =&gt; {<br>  const navigateTo = useNavigate();<br>  const restoreOriginalUri = async (_oktaAuth, originalUri) =&gt; {<br>    navigateTo(toRelativeUrl(originalUri || &quot;/&quot;, window.location.origin));<br>  };<br><br>  return (<br>    &lt;&gt;<br>      &lt;Provider store={store}&gt;<br>        &lt;Security oktaAuth={oktaAuth} restoreOriginalUri={restoreOriginalUri}&gt;<br>          &lt;Routes&gt;<br>            &lt;Route path=&#39;/protected&#39; element={&lt;Authenticated /&gt;}&gt;<br>              &lt;Route path=&#39;&#39; element={&lt;ProtectedComponent /&gt;} /&gt;<br>            &lt;/Route&gt;<br>            &lt;Route path=&#39;/login/callback&#39; Component={LoginCallback} /&gt;<br>{/* &lt;....other routes that needs to be protected &gt; */}<br>          &lt;/Routes&gt;<br>        &lt;/Security&gt;<br>      &lt;/Provider&gt;<br>    &lt;/&gt;<br>  );<br>}<br><br>export default App</pre><p>In the above code, you import Security and LoginCallback components from okta-react. Secure all your routes by wrapping the &lt;Routes&gt; Component with &lt;Security&gt;.</p><p>Import the oktaConfig and pass it your Security component. Security component also take another parameter called “restoreOriginalUri” which can be used to pass a callback function which gets executed on successful authentication.</p><p>We also pass “Authenticated” component to each route that needs to be protected. Below is a sample code. Each time a protected component is called, &lt;Authenticated&gt; component will be executed and handles the redirect/authentication flow.</p><pre>import { useOktaAuth } from &#39;@okta/okta-react&#39;;<br>import React, { useEffect } from &#39;react&#39;;<br>import { toRelativeUrl } from &#39;@okta/okta-auth-js&#39;;<br>import { Outlet } from &#39;react-router-dom&#39;;<br><br>const Authenticated = () =&gt; {<br>  const { oktaAuth, authState } = useOktaAuth();<br><br>  useEffect(() =&gt; {<br>    if (!authState) {<br>      return;<br>    }<br><br>    if (!authState?.isAuthenticated) {<br>      const originalUri = toRelativeUrl(window.location.href, window.location.origin);<br>      oktaAuth.setOriginalUri(originalUri);<br>      oktaAuth.signInWithRedirect();<br>    }<br>  }, [oktaAuth, !!authState, authState?.isAuthenticated]);<br><br>  if (!authState || !authState?.isAuthenticated) {<br>    return (<br>      &lt;div className=&#39;loader&#39;&gt;<br>        {/* your loader component*/}<br>      &lt;/div&gt;<br><br>    );<br>  }<br>  return (&lt;Outlet /&gt;);<br>}<br><br>export default Authenticated;</pre><h3>Integration Steps for NodeJS</h3><p>When you authenticate with Okta on the frontend, you get an accessToken from okta. You need to pass this accessToken on your API calls to the backend. On the backend side, we validate this token and allow for the protected backend routes to be consumed. By this way, we ensure both frontend and backend are protected using Okta.</p><h4>Step 1: Setup NodeJS backend</h4><ul><li>Install okta jwt-verifier. Navigate to your NodeJS application folder and execute.</li></ul><pre>npm install @okta/jwt-verifier</pre><ul><li>In your nodeJs app’s root folder, create an .env file with the following information (or) add to your existing .env if you have one already. Update the OKTA_DOMAIN, it is the same as what you entered in your react app.</li></ul><pre># Okta Config<br>OKTA_DOMAIN=&quot;Your-Okta-Domain&quot;<br>AUTH_SERVER_ID=&quot;default&quot;<br>AUDIENCE=&quot;api://default&quot;</pre><ul><li>Create a folder named “middleware” and in that create “oktaVerifier.js” with following content.</li></ul><pre>import OktaJwtVerifier from &#39;@okta/jwt-verifier&#39;;<br>import dotenv from &#39;dotenv&#39;;<br>dotenv.config()<br><br>const OKTA_DOMAIN = process.env.OKTA_DOMAIN;<br>const AUTH_SERVER_ID = process.env.AUTH_SERVER_ID;<br><br>export const oktaJwtVerifier = new OktaJwtVerifier({<br>  issuer: `https://${OKTA_DOMAIN}/oauth2/${AUTH_SERVER_ID}`<br>});</pre><ul><li>Create a file named “authRequired.js” with following content. In this we get the accessToken from Auth Header passed from frontend react. This token is validated using oktaJwtVerifier.</li></ul><pre>import { oktaJwtVerifier } from &#39;./oktaVerifier.js&#39;;<br>import dotenv from &#39;dotenv&#39;;<br>dotenv.config()<br><br>export const oktaAuthRequired = (req, res, next) =&gt; {<br>  const authHeader = req.headers.authorization || &#39;&#39;;<br>  const match = authHeader.match(/Bearer (.+)/);<br><br><br>  if (!match) {<br>    res.status(401);<br>    return next(&#39;Unauthorized&#39;);<br>  }<br>  const accessToken = match[1];<br>  const audience = process.env.AUDIENCE;<br>  return (<br>    oktaJwtVerifier<br>      .verifyAccessToken(accessToken, audience)<br>      .then((jwt) =&gt; {<br>        req.jwt = jwt;<br>        next();<br>      })<br>      .catch((err) =&gt; {<br>        res.status(401).send(err.message);<br>      })<br>  );<br>};</pre><ul><li>Pass the authRequired.js as a middleware to all your backend routes in NodeJS. In the below example, we have a backend API called “myApi” which is protected using “oktaAuthRequired” imported from “authRequired.js”</li></ul><pre>import express from &quot;express&quot;;<br>import { oktaAuthRequired } from &quot;../middleware/authRequired.js&quot;;<br>const router = express.Router();<br><br>import { myController } from &quot;../controllers/Controller.js&quot;;<br><br>router.post(&quot;/myApi&quot;, oktaAuthRequired, myController)<br><br>export default router;</pre><h3>Summary</h3><p>Here we saw how to integrate Okta with an application that uses React and NodeJS.</p><p>To achieve this, we created a SPA app in the Okta developer portal. clientId and redirectURIs created in SPA app are used in the react app. Unauthenticated users are redirected to Okta login page and upon successful authentication, they are redirected to the callback URL (or a landing page) with an okta token (identityToken and accessToken).</p><p>To make sure that the backend APIs are protected as well using okta app, in every API call we pass the accessToken. We use okta’s jwt-verifier module to verify the accessToken passed from UI is valid.</p><p>By this both ReactJS and NodeJS apps are protected by Okta!</p><blockquote>Thank You!</blockquote><blockquote>Prem</blockquote><blockquote>Follow me <a href="https://www.linkedin.com/in/premkumar-d-117a3a39/">here</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=356d35f7984" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>