Integrate your React app


# Integrate your React app

Follow the steps given below to authenticate users to your React SPA with OpenID Connect using the Asgardeo React SDK (opens new window).

# Prerequisites

In the tutorial,

  • your organization name is referred to as <org_name>.
  • <client_id> refers to the client credential that you obtain once you register your application in Asgardeo.

# Install the SDK

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 --save
1

The react-router-dom package is a peer-dependency of the SDK and it is required for the SDK to work. We are working on making it optional.

# Configure the SDK

SDK uses React Context API (opens new window) under the hood to share the data between components. You can easily integrate Asgardeo in your application by using AuthProvider as the wrapper element to inject configurations.

AuthProvider will provide the session state which contains information such as the authenticated user's display name, email address etc. as well as the methods required to implement authentication in the React app.

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

AuthProvider takes a config object as a prop (opens new window) which is used to initialize the SDK instance. Copy and use the following code within your root component to configure AuthProvider for your application.

Typically, the root component of a react app is defined in the index.* file.

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

const config = {
     signInRedirectURL: "https://localhost:3000/sign-in",
     signOutRedirectURL: "https://localhost:3000/sign-out",
     clientID: "<client_id>",
     baseUrl: "https://api.asgardeo.io/t/<org_name>",
     scope: [ "openid","profile" ]
};

export const MyApp = (): ReactElement => {
    return (
        <AuthProvider config={ config }>
            <App />
        </AuthProvider>
    )
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

Details of the parameters are given below.

Parameter Description
clientID This is the Client ID of your OIDC app. See how to obtain client ID.
baseUrl This is the Asgardeo server's host name along with your organization name.
signInRedirectURL This is the URL the app redirects to after user login. See Authorized redirect URLs.
signOutRedirectURL This is the URL the app redirects to after user logout. See Authorized redirect URLs.
scope The list of OIDC scopes that are used for requesting user information. The openid scope is mandatory to get the ID token. You can add other OIDC scopes such as profile and email.

# Access the session state

The useAuthContext() hook provided by the SDK could be used to access the session state that contains information such as the email address of the authenticated user and to access the methods that are required for implementing authentication.

Once the root component is wrapped with AuthProvider, useAuthContext() hook can be used anywhere within the application.

Use the below code segment to import the useAuthContext() hook from @asgardeo/auth-react.

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

And then inside your components, you can access the context as follows.

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

Few common methods that you can access with useAuthContext() are listed below. These will be helpful when implementing authentication capabilities in your application.

  • state object - This will contain attributes such as whether a user is currently logged in, the username of the currently logged-in user etc.
  • signIn - Initiate a login request to Asgardeo, process the response to obtain authentication response.
  • signOut - Logout the user from Asgardeo and clear any authentication data from the SDK storage.
  • isAuthenticated - Check whether there is an authenticated user session. Based on the result you can decide to change the application view/behaviour.
  • getBasicUserInfo - Get authenticated user's basic information from the authentication response.
  • getDecodedIDToken - Get the decoded id_token obtained in the authentication response. From there you can derive more information such as additional user-attributes.
  • getIDToken - Get the id_token (JWT) obtained in the authentication response.
  • getAccessToken - Get the access_token obtained in the authentication response.
  • refreshAccessToken - Get the refresh_token obtained in the authentication response.

Methods related to the token such as getIDToken, getDecodedIDToken, getAccessToken and refreshAccessToken are only available if the storage mechanism is set to sessionStorage or localStorage in the SDK configuration. If it is set to webWorker, an error is thrown since the token is stored inside the web worker and cannot be accessed by outside party.

# Use the API

You can now start using the SDK's API to implement the required authentication logic. Follow the instructions given below to implement each use case.

# Access the state object

The state object contains attributes of a user. Its structure is as follows.

{
    "allowedScopes": "openid profile",
    "displayName": "alica",
    "isAuthenticated": true,
    "isLoading": false,
    "sub": "d33ab8c0-1234-4567-7890-b5c3619cb356",
    "username": "[email protected]",
    "isSigningOut": false
}
1
2
3
4
5
6
7
8
9

The isAuthenticated attribute checks whether a user is currently logged in via Asgardeo or not.

# Add login to your application

You can use the useAuthContext hook from the Asgardeo React SDK to easily authenticate your React application.

Implement a login button as follows using the signIn() function in the useAuthContext hook.

<button onClick={ () => signIn() }>Login</button>
1

Clicking on the Login button will take the user to the Asgardeo login page. Once signIn() succeeds, the user will be redirected to the app (based on the signInRedirectURL specified in the AuthProvider configuration) and the state.isAuthenticated will be set to true.

# Get access token

Once the user is logged in with Asgardeo, the application can get the access token issued by Asgardeo.

See the SDK reference (opens new window) for more information.

const { getAccessToken } = useAuthContext();

useEffect(() => {
    getAccessToken().then((accessToken) => {
        //console.log(accessToken);
    }).catch((error) => {
        //console.log(error);
    });
}, []);
1
2
3
4
5
6
7
8
9

Sample access token is given below:

61985b0e-26c3-38b7-acff-b18ad934eafc
1

# Get user information

In addition to implementing login and logout, you can also use the SDK to get user information.

There are two ways for you to get user information:

  • Get user information from a decoded ID token.
  • Use the getBasicUserInfo() API and get basic user information.

getBasicUserInfo() can be used as follows.

const { getBasicUserInfo } = useAuthContext();
  
getBasicUserInfo().then((basicUserDetails) => {
    console.log(basicUserDetails);
}).catch((error) => {
    // Handle the error
})
1
2
3
4
5
6
7

basicUserDetails object will have a structure similar to below:

{
    "allowedScopes": "openid",
    "sessionState": "eb0e12f9a113f49ffef887a464c7980d84bb5b11dfeb1774309aee9b88c83c21.8-LXzzHCUSOOa2GeH-LFfA",
    "username": "[email protected]",
    "country": "Sri Lanka",
    "email": "[email protected]"
}
1
2
3
4
5
6
7

You can get additional information from the user by requesting user information from Asgardeo using scopes

# Get decoded ID token

Once the user is logged in with Asgardeo, the application can get the ID token issued by Asgardeo.

The SDK provides the getDecodedIDToken() API to get the decoded token. You can use this decoded token to obtain user claims as below.

const { getDecodedIDToken } = useAuthContext();

getDecodedIDToken().then((decodedIDToken) => {
    console.log(decodedIDToken);
}).catch((error) => {
    // Handle the error
})
1
2
3
4
5
6
7

Sample decoded ID token object is given below:

{
    "isk": "329d5bf5732791509edabb093d78a4a2665dbc65d99119f45f1d4db1a2459cf1",
    "at_hash": "TN1HIyOnt_8shS2DalrdfQ",
    "sub": "[email protected]",
    "country": "Sri Lanka",
    "amr": [
        "BasicAuthenticator"
    ],
    "iss": "https://api.asgardeo.io/t/bifrost/oauth2/token",
    "sid": "81a61d37-9a6d-487a-8f5f-c7a313c44c31",
    "aud": "SmLpPiRube64JmkAf4nhZVD_6V8a",
    "c_hash": "1pWTMQ7ZTxCWSapucJF-bw",
    "nbf": 1627966715,
    "azp": "SmLpPiRube64JmkAf4nhZVD_6V8a",
    "exp": 1627970315,
    "iat": 1627966715,
    "email": "[email protected]"
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

From the decoded ID Token(decodedIDToken) object, you can get the following information:

sub decodedIDToken.sub
email decodedIDToken.email
country decodedIDToken.country

You can loop through the decodedIDToken object and get the other claims as well.

# Add logout to your application

We can use the signOut() method from useAuthContext() hook to implement a logout button.

<button onClick={ () => signOut() }>Logout</button>
1

Clicking on the Logout button will sign out the user. The user will then be redirected to the signOutRedirectURL (specified in the AuthProvider configuration) and the state.isAuthenticated will be set to false.

You can use the state.isAuthenticated attribute to check the authentication status of the user.

# Add Routing

If your application needs routing, the SDK provides a component called SecureRoute, which is implemented with react-router-dom. This component allows you to easily secure your routes with Asgardeo. You can learn more about routing here (opens new window).

# More Information

If you want to learn in-depth about the Asgardeo React SDK, you can refer to the Asgardeo React SDK documentation (opens new window).