How to integrate okta with react / Implementing Okta authentication in a React app

 How to integrate okta with react / 
Implementing Okta authentication in a React app

for demo please follow my git repo

1).Before starting implementing react first create okta demo account using react website


b).register page 

c).after login go to dashboard page 

d).after that create application in okta account

e).after click on create application page and create application (for open SS0-signle sign on need 
to create two application one for API like dot, python, php other for front end like react or angular)

f).in this list first select open id connection then select type of application first i select API app 
for backend application 

g).fill form after next button click 

h).after successfully create app just go to security tab and select api from side menu 

i).then go to trusted origin tabs and add your host of api and frontend site where its hosted

j). now just create new application for front end same step as API create 
step ->application ->create app ->select openID ->select single page application 

k).finally press submit to create application 

l).after creating application of front end just need to assign added user 
 1)create user : go to dictionary->add people

       and now click on add person and fill form and save to create new users

if you want to allow register user facility from login page just need to follow steps and 

      after create user assign a user or group to perticular app just need to follow step
         application ->assign to app ->choose app from left side and then choose user from list

        and then finally press save button


m).now you need to follow final steps use "issuer" and app key from your application 
for copy issuer url just need to follow steps
goto security ->select api->authorization server tab->issuer url 
for example: ""

for client id just need to follow steps
applications-> application ->copy client id from app


Now you need to programing in react just follow 

a).first you need to add browser routing to top level of app component 

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter as Router } from 'react-router-dom';
const root = ReactDOM.createRoot(document.getElementById('root'));
    <Router><App /></Router>

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more:

b).then setup app.js component 

import { SecureRoute, Security, LoginCallback } from '@okta/okta-react';
import { OktaAuth, toRelativeUrl } from '@okta/okta-auth-js';
import { BrowserRouter, Route,  useHistory } from 'react-router-dom';
import './App.css';
import Home from './feature/Home/Home';
import Dashboard from './feature/Dashboard/Dashboard';
import { withRouter } from 'react-router-dom';
import { useCallback } from 'react';

const App = () => {
  const oktaAuth = new OktaAuth({
    issuer: '',
    clientId: '0oa6lpvx0yt0wRwPi5d7',
    redirectUri: window.location.origin + '/callback',
  const customAuthHandler = () =>{
  const history = useHistory();
  const restoreOriginalUri  = useCallback(async (_oktaAuth, originalUri) => {
    history.replace(toRelativeUrl(originalUri || '/', window.location.origin));
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  return (
    <Security oktaAuth={oktaAuth} restoreOriginalUri={restoreOriginalUri} onAuthRequired={customAuthHandler} >
    <SecureRoute path='/' component={Home} />
    <SecureRoute path='/Dashboard' component={Dashboard} />
    <Route path='/callback' component={LoginCallback} />

const AppWithRouterAccess = withRouter(App);
const RouterApp = () => (<BrowserRouter><AppWithRouterAccess /></BrowserRouter>);
export default RouterApp;

c).now finally you need to print use info

import React, { useState, useEffect } from 'react';
import { useOktaAuth } from '@okta/okta-react';
const Home = () =>{
    const { authState, oktaAuth } = useOktaAuth();
    const [userInfo, setUserInfo] = useState(null);
    useEffect(() => {
      if (!authState || !authState.isAuthenticated) {
      } else {
    }, [authState, oktaAuth]); // Update if authState changes
    const logout = async () => {
      await oktaAuth.tokenManager.clear();
      await oktaAuth.signOut();

    if (!userInfo) {
      return (
          <p>Fetching user profile...</p>
    return (
          <header as="h1">
                        {' '}
            My User Profile (ID Token Claims)
            your Access Token is "{ authState.accessToken.accessToken }" <button onClick={ ()=>logout() }>logout</button>
            and is now stored in local storage.
            This route is protected with the
            {' '}
            {' '}
            component, which will ensure that this page cannot be accessed until you have authenticated.
              {Object.entries(userInfo).map((claimEntry) => {
                const claimName = claimEntry[0];
                const claimValue = claimEntry[1];
                const claimId = `claim-${claimName}`;
                return (
                  <tr key={claimName}>
                    <td id={claimId}>{claimValue.toString()}</td>

export default Home;



Featured Post

how to find n number of nodes have child or cildren

 how to find n number of nodes have child or cildren for that we use recursive function  const   data = {     'id' : '0' ,...

Popular Posts