Simplify React App Login with Asgardeo

Savindi Waduge
Identity Beyond Borders
9 min read6 days ago

Introduction

React is a popular JavaScript library for building dynamic single-page applications. It allows developers to create responsive interfaces by breaking down complex UIs into reusable components.

Adding a login system to your React app is essential for managing user access and personalizing experiences. It secures user data and enhances engagement.

Security is crucial for protecting user information and complying with regulations like GDPR and CCPA. Using tools like Asgardeo for identity and access management can help implement a secure login system efficiently.

In this guide, we’ll show you how to Implement user login in your React app and integrate with a OpenID Connect based Identity Provider (IdP) making the login process simple and secure.

Here are the steps we will follow,

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

Step 1 : Create your React App

If you want to try out this sample application without going through this guide, 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. Run the following command to create your first React sample application. You need to install npm to run this sample unless npm is already installed in your environment.

npm create vite@latest

Step 2 : Integrate a login SDK

Implementing a login page using OpenID Connect involves several tasks, such as rendering login/logout links, making an OpenID Connect request from the application to the Identity provider with the necessary security controls, validating the IDToken returns by the IdP, retrieving the user attributes from the IDToken, retrieving refresh tokens and access tokens, handling the logout request etc. It’s perfectly ok to implement these capabilities by yourself but you don’t need to do so, because there are production-grade login SDKs available to simplify the above tasks.

Integrating your application with an identity provider simplifies user authentication and ensures secure access to resources, offloading complex tasks like credential management and session handling.

In this guide, we demonstrate using Asgardeo for seamless and secure authentication, applicable to any modern identity provider.

The Asgardeo Auth React SDK lets React apps use Asgardeo for authentication. It offers features such as user authentication, showing 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 an identity provider like 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.

Step 3 : Integrate with an Identity Provider

If your user login requirements are simple, probably you can implement a login module backed by a simple database table, but when you encounter additional user login requirements such as multi-factor authentication (MFA), social logins, account provisioning and account management requirements you will end up spending more time implementing, testing and maintaining standard Identity and access management (IAM) capabilities that are readily available with IAM solutions rather than worrying on your core business capabilities.

In this guide we will use Asgardeo as the identity provider for our application.

What is Asgardeo?

Asgardeo is a developer-focused cloud identity solution that makes it easy to add secure login and manage user identities in your apps. It simplifies authentication with ready-to-use templates, SDKs, and guides, boosting developer efficiency. Asgardeo ensures top-notch security and compliance, supporting standard protocols and adaptive authentication.

Now, let’s configure our created application with Asgardeo.

Sign up for Asgardeo

If you have not already set up an account in Asgardeo, Create an account and 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 wizard popup 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.

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.

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;

signInRedirectURL — The URL to redirect to after the user authorizes the client app. eg: https//localhost:3000/sign-in

signOutRedirectURL — The URL to redirect to after the user

clientID — The client ID of the OIDC application hosted in the Asgardeo.

baseUrl — The origin of the Identity Provider. eg: https://www.asgardeo.io/t/<org_name>

scope — Specifies the requested scopes.

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.

useAuthContext is a React hook that returns the session state that contains information such as the email address of the authenticated user and the methods that are required for implementing authentication.

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

Step 4 : Add Secure Login to Your React App

Let’s implement Asgardeo authentication in the React app.

Create a user

First, let’s create a user who will access our app (read more)

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

Set up login/logout functionality

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/<org_name>",
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.

Refer to the final code here.

Now, let’s start the app (npm run dev from root) and see what it looks like.

This is what my sample app looks like.

As we have added a Sign In button, clicking it will redirect you to the Asgardeo login page. There’s no need to create sign-in forms in your app! 💃

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

In summary, Asgardeo simplifies adding authentication to a React app by providing an easy-to-integrate IDaaS platform. By configuring the Asgardeo Auth React SDK and using the useAuthContext hook, developers can quickly implement secure login/logout functionality without creating custom sign-in forms.

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.

Eg:

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>
)
};
//rest of the code.

We can have a fallback page to include the page to direct to if the user isn’t authenticated.

Sample code

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.

Eg:

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

Sample Code

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>

Sample code

In summary, Asgardeo’s SDK offers ways and components like SecureApp and AuthenticatedComponent to ensure only authenticated users can access specific routes or areas within a React app.

To fully leverage the capabilities of modern web applications, it’s essential to securely access APIs that provide critical data and services. This ensures that sensitive information is protected and only available to authenticated users. Here’s how you can use Asgardeo’s SDK to make secure API requests:

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*.

Note — 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);
});
}, [])
}

After creating a basic Asgardeo secure 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! 🚀

--

--