React App Authentication with Asgardeo

Savindi Waduge
Identity Beyond Borders
7 min readMay 26, 2024

Asgardeo is a developer-focused, identity-as-a-service (IDaaS) platform that simplifies application login experiences and identity and access management. In layman’s terms, Asgardeo allows you to add authentication to your application in just a few minutes. And most importantly, security and compliance is at Asgardeo’s Core.

Here are the steps we will follow in this guide to securing a React app with Asgardeo,

Grab a cuppa, let’s get started! ☕️

Sign up for Asgardeo

Create an account in Asgardeo.

After you sign up, you will be redirected to the Asgardeo Console .

Create an Application

Next, let’s register your React app in Asgardeo.

  1. On the Asgardeo Console, go to Applications.
  2. Click New Application
  3. Select Single-Page Application.

4. Complete the form with a suitable name and an authorized redirect URL.

Note — authorized redirect specifies where Asgardeo should direct users once they’ve successfully logged in. Usually, it’s the web address where your application is hosted (example: http://localhost:3000).

Once you create the application, you will be directed to the Quick Start tab of the created application which will guide you to integrate login to your application in several technologies like React, Angular and Vanilla Javascript.

In this blog, we will be using a React app.

Integrate the Asgardeo Auth React SDK

There are 2 ways you can start integrating Asgardeo into a React app.

You can use the sample React app here with the necessary boilerplate.

For this guide, I’m going to create a simple React app using Vite.

npm create vite@latest

Optionally, I’ve switched my Vite React app’s port to 3000. You can configure this by following their guide.

Here’s my vite.config.ts file:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
base: "/",
plugins: [react()],
preview: {
port: 3000,
strictPort: true,
},
server: {
port: 3000,
strictPort: true,
host: true,
origin: "http://0.0.0.0:3000",
},
});

Let’s get the application ready.

  • Integrate the Asgardeo Auth React SDK or library.

The Asgardeo Auth React SDK lets React apps use Asgardeo for authentication. It offers features such as user authentication, access to user info, and HTTP hook to send requests attaching Asgardeo tokens.

Check out its list of APIs.

Run the following command to install the React SDK and the necessary dependencies from the npm registry.

npm install @asgardeo/auth-react react-router-dom

Note — react-router-dom is a package that enables navigation and routing functionalities within React applications. and we need this when discussing Securing Routes in the App.

  • Configure the <AuthProvider />

The AuthProvider component allows you to integrate Asgardeo into your app. To do that, wrap the application with the AuthProvider component.

AuthProvider takes a config object as a prop which is used to initialize the SDK instance.

Hint — Use the information available in the Quick Start tab of your app or the Quickstart guide under the React SDK for the AuthProvider config.

import { AuthProvider } from "@asgardeo/auth-react";

const authConfig = {
signInRedirectURL: "http://localhost:3000",
signOutRedirectURL: "http://localhost:3000",
clientID: "<client_ID>",
baseUrl: "https://api.asgardeo.io/t/<org_name>",
scope: [ "openid","profile" ]
};

const App = () => {

return (
<AuthProvider config={authConfig}>
<App />
</AuthProvider>
)
}

export default App;

Once you’ve added the AuthProvider to the root component, you can use the useAuthContext() hook anywhere in your app to handle user authentication easily.

Note — You can refer to more details about AuthProvider config here.

Adding Secure Login to Your React App

Let’s implement Asgardeo authentication in the React app.

First, let’s create a user who will access our app.

  1. Go to Asgardeo Console > User Management > Users.
  2. Click Add Users > Single User.
  3. Add the user information and Finish.

Next, let’s set up a simple login/logout functionality.

The useAuthContext() hook helps implement authentication functions and access session data, like whether the user is logged in and their unique ID.

import { AuthProvider } from "@asgardeo/auth-react";
import { useAuthContext } from "@asgardeo/auth-react";

const authConfig = {
signInRedirectURL: "http://localhost:3000",
signOutRedirectURL: "http://localhost:3000",
clientID: "<client_ID>",
baseUrl: "https://api.asgardeo.io/t/savindi",
scope: [ "openid","profile" ]
};

const AppContent = () => {
const { state, signIn, signOut } = useAuthContext();

if (state.isAuthenticated) {
return <button onClick={signOut}>Logout</button>;
} else {
return <button onClick={signIn}>Login</button>;
}
};

const App = () => (
<AuthProvider config={authConfig}>
<AppContent />
</AuthProvider>
);

export default App;

The state object contains information of the authenticated user. Its structure is as follows.

{
"allowedScopes": "openid profile",
"displayName": xxxxxx,
"email": xxxxxx,
"userid": xxxxxxx,
"isAuthenticated": true,
"isLoading": false,
"isSigningOut": false
"sub": "xxxxxx",
"username": "xxxxxxxx",
}

In addition to the state object, signIn and signout methods, the hook also returns other methods.

Once you add the Sign In button, clicking it will redirect you to the Asgardeo login page. There’s no need to create sign-in forms within your app! 💃

Now, enter the credentials of the newly created user, click Sign In, and you’ll be directed to the Authorized Redirect URL (http://localhost:3000). It’s that easy!

Securing Routes within the App

By securing routes, you ensure that only authenticated users with the appropriate permissions can access sensitive areas of the application.

The SDK provides multiple approaches to secure routes in your application.

  1. Securing a route using the SDK

With this approach only authenticated users will be taken to the route.

//App.tsx
import { AuthProvider, useAuthContext } from "@asgardeo/auth-react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Home from "./pages/Home";
import Contact from "./pages/Contact";
import PageNotFound from "./pages/PageNotFound";
import "./App.css";
import Unauthenticated from "./pages/Unauthenticated";
import { ReactNode } from "react";

const authConfig = {
signInRedirectURL: "http://localhost:3000",
signOutRedirectURL: "http://localhost:3000",
clientID: "<client_ID>",
baseUrl: "https://api.asgardeo.io/t/<org_name>",
scope: ["openid", "profile"]
};

const AppContent = () => {

const ProtectedRoute = ({ children }: { children: ReactNode }) => {
const { state } = useAuthContext();

if (!state.isAuthenticated) {
return <Unauthenticated />;
}

return children;
};

return (
<Routes>
<Route
path="/contact"
element={
<ProtectedRoute>
<Contact />
</ProtectedRoute>
} />
<Route path="/" element={<Home />} />
<Route path="*" element={<PageNotFound />} />
</Routes>
)
};

const App = () => (
<AuthProvider config={authConfig}>
<Router>
<AppContent />
</Router>
</AuthProvider>
);

export default App;

We can have a fallback page called Unauthenticated.tsx like below to include the page to direct to if the user isn’t authenticated.

//Unauthenticated.tsx
import { useAuthContext } from "@asgardeo/auth-react";
import { useNavigate } from "react-router-dom";

const Unauthenticated = () => {
const { signIn } = useAuthContext();
const navigate = useNavigate();

return (
<div>
<h5>You need to be logged in to access this page</h5>
<div className="button-container">
<button className="text-button" onClick={() => navigate("/")}>
Go Back
</button>
<button onClick={() => { signIn() }}>Login</button>
</div>
</div>
);
};

export default Unauthenticated;

2. SecureApp

This component wraps a React component and renders it only if the user is signed in securing the whole React app. Otherwise, it renders the fallback component.

If the user is not signed in, this component automatically initiates the sign-in flow.

<SecureApp
fallback={ <Loader /> }
onSignIn={ onSignInFunction }
overrideSignIn={ overrideSignInFunction }
>
<App />
</SecureApp>

3. AuthenticatedComponent

If the user is authenticated, the component displays the wrapped content. If not, it shows the fallback component passed in, which can be any React element.

If you don’t include a fallback, it will render a null.

<AuthenticatedComponent
fallback={ <FallbackComponent /> }
>
<SecureComponent />
</AuthenticatedComponent>

Accessing a Protected API

Once the user is authenticated and you have obtained an access token from Asgardeo, you can use this token to access protected API endpoints. You can use the httpRequest API provided by the Asgardeo SDK to make HTTP requests to these endpoints.

This method is used to send http requests to Asgardeo or desired backend. The developer doesn’t need to manually attach the access token since this method does it automatically*.

*The storage type must be set to webWorker for the token to be automatically attached. If it’s set to sessionStorage or localStorage, you can implement your own method for attaching the access token to the header.

Here’s a simple example of how you might use the Asgardeo SDK’s httpRequest to call a protected API endpoint, such as /scim2/me (to get the user profile details after signing in):

import { useAuthContext } from "@asgardeo/auth-react";

const App = () => {
const { httpRequest } = useAuthContext();

const requestConfig = {
headers: {
"Accept": "application/json",
"Content-Type": "application/scim+json"
},
method: "GET",
url: "https://api.asgardeo.io/t/<org_name>/scim2/me"
};

useEffect(() => {
// Make a GET request to a protected endpoint
httpRequest(requestConfig)
.then((response) => {
// Handle successful response
console.log('Response:', response.data);
})
.catch((error) => {
// Handle error
console.error('Error:', error);
});
}, [])
}

In this example, we’re attaching the access token in the Authorization header of the HTTP request using the Bearer authentication scheme.

Code

After creating a basic Asgardeo secured app, there’s more to explore! By utilizing Asgardeo, we can add various features such as:

Keep exploring and powering up your app with Asgardeo’s vast capabilities. Happy coding! 🚀

--

--