Secure Your React SPAs With Choreo Managed Authentication

Stefinie Fernando
Choreo Tech Blog
Published in
8 min readJun 7, 2024

--

Photo by Jornada Produtora on Unsplash

Building dynamic and engaging Single-Page Applications (SPAs) with React is a breeze. You can craft beautiful user interfaces and intuitive user experiences with minimal effort using React. However, to build truly useful applications, you need a secure and seamless way for users to log in, manage their accounts, and interact with your backend data. The communication between frontend and backend usually happens over the internet, which by its very nature is accessible to everyone. Hence, handling this communication securely is crucial. To securely manage communication between the frontend and backend, two main requirements must be met: Firstly, you need to authenticate users and get the required information about them (Authentication), secondly you need to protect services and securely access these protected services (Authorization).

Over the years, the way we implement these security measures has evolved, with protocols like OAuth2/OpenID Connect now being widely used. While there are many libraries in the React ecosystem that simplify the implementation of authentication and authorization in your React application, a fundamental understanding of these protocols and a certain level of expertise is required to use these libraries efficiently. Moreover, when it comes to SPAs, additional measures are necessary to securely manage access tokens on the application side, as the JavaScript code in your browser is vulnerable to attacks like Cross-Site Scripting (XSS) and Cross Site Request Forgery (CSRF).

Choreo’s managed authentication feature helps to eradicate the burden of handling authentication and authorization in your React SPAs by allowing you to easily and securely implement authentication and authorization without needing to understand complex security protocols. This feature uses the backend for frontend (BFF) architecture, a secure method recommended for browser-based apps using OIDC/OAuth2.0. This approach keeps OAuth tokens safe from browser-side code, protecting them from XSS and CSRF attacks. Managed Authentication feature provides you with following capabilities:

  1. Setup login and logout functionalities for your SPAs
  2. Retrieve logged-in user information
  3. Session management
  4. Secure API invocation

As a developer, you can easily set up Choreo managed authentication to seamlessly integrate authentication into your React SPA. Let’s see how we can do this step by step. Throughout this guide I will use the sample React app with managed authentication and the reading list back-end service as a reference.

Prerequisites

  1. Deploy your BE service on Choreo
  2. Create a web application component on Choreo using your React SPA repository
  3. Create a connection from your frontend app to consume the backend service

Check the Choreo documentation on how to get your backend and frontend apps running on Choreo.

Step 1: Setup managed authentication in your React SPA

Step 1.1: Implement the sign-in functionality
First things first, in order to handle authentication in a web application there needs to be a Sign In/ Login button. To allow Choreo to manage the sign-in functionality of your React SPA, you must implement a sign-in button that redirects users to `auth/login` path on click. You can use the following code snippet or any custom button component from a preferred UI component library:

<button onClick={() => {window.location.href="/auth/login"}}>Login</button>

With the above code snippet when a user clicks on the Login button, Choreo will redirect the user to the configured identity provider and handle the authentication process, conforming to the OICD/OAuth2.0 protocols. On successful sign-in, Choreo will set the relevant session cookies and redirect the user to the post-sign-in path. The default post sign-in path is ‘/’. We will see how we can configure a different path in the latter part of this guide.

Step 1.2 : Obtain user information claims

On successful login, your application can access the logged in user’s information using 2 ways:

  1. Via the ‘userinfo’ cookie
  2. Via the user information GET endpoint

Via the ‘userinfo’ cookie

Choreo’s managed authentication establishes a ‘userinfo’ cookie that is accessible from the post-sign-in path you configured. This ‘userinfo’ cookie, provided by the identity provider, contains encoded user information claims. This cookie is intentionally set to have a short lifespan. As developers you can decide how to utilize the user information obtained from the cookie. Following is a code example on how to parse the cookie using ‘js-cookie’ library and obtain the user information. You can use any cookie-parsing library of your choice.

 import Cookies from 'js-cookie';

// Read userinfo cookie value.
const encodedUserInfo = Cookies.get('userinfo')

// Decode the value.
const userInfo = JSON.parse(atob(encodedUserInfo))

// Store the value in a preferred browser-based storage if needed.

// Clear the cookie.
Cookies.remove('userinfo', { path: <post-login-path> })

Via a GET endpoint

User information can also be retrieved using the GET endpoint ‘/auth/userinfo’. You can use this endpoint to query information about users who have signed in. It also serves as a mechanism to check the state of a user who has signed in.

Following is an example of a request to this endpoint:

const response = await fetch('/auth/userinfo');

If a user has signed in, the server sends a 200 OK response with the user information in JSON format in the response body. However, if the user is not signed in, the server sends a 401 Unauthorized response.

Step 1.3: Implement the sign-out functionality

Similar to the sign-in button we need to implement the logout functionality of our application as well.

<button onClick={async () => {
window.location.href = `/auth/logout?session_hint=${Cookies.get('session_hint')}`;
}}>Logout</button>`

Above example uses the previously used `js-cookie` library for cookie parsing. When a user clicks the sign-out button, Choreo will clear the session cookies and redirect the users to the OIDC logout endpoint of the configured identity provider.

Step 1.4: Invoke APIs

In order invoke the backend service from your frontend app you need to create a connection (prerequisite #3). To invoke Choreo APIs within the same organization as your web application, you can use the relative path /choreo-apis/<api-suffix>, regardless of whether managed authentication is enabled for the web application or not.

For example, if the API URL is https://3fe77b4a-67f5-4460-a8e9-1140da68d971-dev.e1-us-east-azure.choreoapis.dev/reading-list-project/reading-list-service/v1.0, the <api-suffix> would be /reading-list-project/reading-list-service/v1.0. You can invoke the API using the /choreo-apis/reading-list-project/reading-list-service/v1.0 relative path from your single-page application.

const response = await fetch('/choreo-apis/<api-suffix>')

If you enable Choreo’s managed authentication, you don’t have to manually add any logic to attach an access token to the API call because Choreo APIs accept the cookies set by Choreo’s managed authentication. You can directly invoke the API as follows:

If Choreo’s managed authentication is disabled, you must ensure that your web application attaches a valid access token to the API call.
Additionally you can also handle session refresh and configure a custom error page with Choreo managed authentication. For the sake of simplicity, we will not look into detail on how to configure them in this guide.

Now that you have done all the necessary steps to implement Choreo managed authentication in your React application, you can commit and push these changes to your repository. Next you can build the latest changes of your application from the Build page.

Step 2: Enable managed authentication and configure the paths

To ensure that your web application functions seamlessly with managed authentication, it is essential to enable managed authentication for your web application component within Choreo at deploy time. Assuming that you have already created a web application component and triggered a build with your latest changes, follow the steps below to enable managed authentication for your application:

  1. From the component listing Select the web application you created in the previous steps
  2. In the left navigation menu, click Deploy
  3. In the Set Up card, click Configure & Deploy

4. Add the necessary configurations for your component.

For an example you can have the api-suffix of your backend service as a configuration here.

window.configs = {
apiUrl: '/choreo-apis/reading-list-project/reading-list-service/v1.0',
};

5. Click Next

6. Make sure Managed Authentication with Choreo toggle is enabled.

7. Specify appropriate values for the following fields

  • Post Login Path — /
  • Post Logout Path — /

One thing to note here is that when you enable managed authentication, Choreo’s built in identity provider will be automatically configured for you. You can upload a userstore file or create some sample users in this identity provider, in order to try out this feature.

However in a real world production level use case you may need to connect a third party identity provider to Choreo in order to manage authentication of your React application.

Since there are no users created in the identity provider yet, click on Create under Manage Users section and create a sample user. Copy the username and the password of the created user which we can use to try out the application later on.

Refer to Configure a User Store with the Built-In Identity Provider for details on adding test users in Choreo built-in identity provider.

8. Finally click Deploy

If you need to change these configurations after you deploy the component, you can click Authentication Settings on the Set Up card, make the necessary changes, and deploy the component once again.

9. Test your application

Click on Web App URL on the Development environment card. This will open up your React application in a new browser tab. Now you can test the end to end functionality of your application including login and api invocations.

Step 3: Configure Identity Provider (Optional)

As mentioned previously in this article, when you enable the managed authentication feature for your application, Choreo automatically configures the built in IdP for you. However this is not recommended for actual production use cases.

For production use cases you can either configure Asgardeo or any other third party IdP of your choice that supports OIDC/OAuth2.0 protocols. Refer the links below on how to configure the IdPs

  1. Configure Asgardeo as an External Identity Provider (IdP)
  2. Configure Azure Active Directory (Azure AD) as an External Identity Provider (IdP)

Once you have set up the IdP, follow the below steps to configure the IdP to work with your React application.

  1. Go to the component page of your React application
  2. Navigate to Settings page from the left menu
  3. Under the Authentication Keys tab, select the preferred environment you want to set up the IdP.
  4. In the Identity Provider list, select your identity provider.

5. Paste the Client ID and Client Secret of the OIDC/OAuth2.0 application you created in your external identity provider.

6. Click Add Keys.

Conclusion

Setting up authentication for your React SPA is now easier than ever with Choreo’s managed authentication. It takes care of everything, from handling logins to securing API access without you having to worry about complex OAuth/OIDC protocols or managing tokens yourself. Signup for free today and see how Choreo can help you take your React applications to the next level. With Choreo, you can focus on building great applications, and let us worry about the rest.

--

--