### Install Dependencies and Start Application Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/samples/asgardeo-react-app/README.md Run these commands in the terminal to install project dependencies and start the development server. ```bash npm install && npm start ``` -------------------------------- ### Run Server Application Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/samples/asgardeo-choreo-react-express/README.md Navigate to the server directory, install dependencies, build the application, and then start the server. The server will be accessible at https://localhost:8080. ```bash 1. cd apps/server 2. npm install && npm run build 2. npm run start ``` -------------------------------- ### Run Client Application Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/samples/asgardeo-choreo-react-express/README.md Navigate to the client directory and install dependencies, then start the client application. The client app will be accessible at https://localhost:3000. ```bash 1. cd apps/client 2. npm install && npm run start ``` -------------------------------- ### Install Asgardeo Auth React SDK Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/README.md Install the SDK package using npm. This command adds the necessary library to your project. ```bash npm install @asgardeo/auth-react --save ``` -------------------------------- ### Example Commit Message Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/HACKTOBERFEST.md Write clear and descriptive commit messages to explain your changes. ```bash Ex: Add support for custom params in the token request ``` -------------------------------- ### Install Dependencies for Asgardeo Auth React SDK Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/README.md Installs the necessary dependencies for the Asgardeo Auth React SDK monorepo. This command should be run from the root of the repository. ```bash yarn build ``` -------------------------------- ### Setup AuthProvider Context Source: https://context7.com/asgardeo/asgardeo-auth-react-sdk/llms.txt Wrap your React application with AuthProvider to initialize the SDK and manage authentication state. Configure sign-in/out redirect URLs, client ID, base URL, scopes, and token storage. ```typescript import React from "react"; import ReactDOM from "react-dom/client"; import { AuthProvider } from "@asgardeo/auth-react"; import App from "./App"; const config = { signInRedirectURL: "https://localhost:3000/sign-in", signOutRedirectURL: "https://localhost:3000/dashboard", clientID: "your-client-id-from-asgardeo", baseUrl: "https://api.asgardeo.io/t/your-org-name", scope: ["openid", "profile", "email"], storage: "sessionStorage", // "sessionStorage" | "localStorage" | "webWorker" resourceServerURLs: ["https://api.example.com"], // Required for webWorker storage disableTrySignInSilently: true, disableAutoSignIn: true }; const root = ReactDOM.createRoot(document.getElementById("root")); root.render( Initializing authentication...} onSignOut={() => console.log("User signed out")} > ); ``` -------------------------------- ### AuthStateInterface Example Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md An example of the AuthStateInterface object, which contains user session details like authentication status, username, and scopes. ```json { "allowedScopes": "openid profile", "displayName": "alica", "isAuthenticated": true, "isLoading": false, "sub": "d33ab8c0-1234-4567-7890-b5c3619cb356", "username": "alica@bifrost.com", "isSigningOut": false } ``` -------------------------------- ### Asgardeo SDK Configuration Example Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md This JSON object shows a sample configuration for the Asgardeo SDK, including client ID, base URL, redirect URLs, scopes, and storage mechanism. The `storage` attribute can be set to 'sessionStorage', 'webWorker', or 'localStorage'. ```json { "clientID": "", "baseUrl": "https://api.asgardeo.io/t/", "signInRedirectURL": "https://localhost:3000/sign-in", "signOutRedirectURL": "https://localhost:3000/sign-out", "scope": ["openid", "profile"], "storage": "sessionStorage" } ``` -------------------------------- ### Making HTTP Requests from Non-Component Logic Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md For sending HTTP requests from JavaScript or TypeScript logic files outside of React components, you need to obtain an instance of the `AsgardeoSPAClient`. This example shows how to fetch user profile details using this client. ```APIDOC ## GET /scim2/me (from non-component) ### Description Fetches the authenticated user's profile details from a non-component context using `AsgardeoSPAClient`. ### Method GET ### Endpoint `https://api.asgardeo.io/t//scim2/me` ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```typescript import { AsgardeoSPAClient } from "@asgardeo/auth-react"; const spaClient = AsgardeoSPAClient.getInstance(); const getUser = () => { const requestConfig = { headers: { "Accept": "application/json", "Content-Type": "application/scim+json" }, method: "GET", url: "https://api.asgardeo.io/t//scim2/me" }; spaClient.httpRequest(requestConfig) .then((response) => { // do something with response }) .catch((error) => { // do something with error. }); }; ``` ### Response #### Success Response (200) - **response** (object) - User profile details. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Making HTTP Requests within React Components Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md When sending HTTP requests from within React components or hooks, utilize the `httpRequest` and `httpRequestAll` methods provided by the `useAuthContext` hook. This example demonstrates fetching user profile details from the SCIM2 `/me` endpoint. ```APIDOC ## GET /scim2/me ### Description Fetches the authenticated user's profile details. ### Method GET ### Endpoint `https://api.asgardeo.io/t//scim2/me` ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```typescript 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//scim2/me" }; useEffect(() => { httpRequest(requestConfig) .then((response) => { // console.log(response); }) .catch((error) => { // console.error(error); }); }, []) // ... other component logic } ``` ### Response #### Success Response (200) - **response** (object) - User profile details. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Configure Sample App Details Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/SAMPLE_APPS.md Update this JSON file with your registered application's client ID, Asgardeo base URL, and redirect URLs for sign-in and sign-out. Ensure the scope includes 'openid' and 'profile'. ```json { "clientID": "", "baseUrl": "https://api.asgardeo.io/t/", "signInRedirectURL": "https://localhost:3000", "signOutRedirectURL": "https://localhost:3000", "scope": [ "openid","profile" ] } ``` -------------------------------- ### Configure Server .env File Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/samples/asgardeo-choreo-react-express/README.md Copy and rename `.env.example` to `.env` in the `apps/server` directory. Update the file with your registered app details from Asgardeo and Choreo portals. ```env NODE_PORT=8080 NODE_ENV=production // Can use a tool like https://1password.com/password-generator to generate the secret SECRET_COOKIE_PASSWORD= ASGARDEO_CLIENT_ID= ASGARDEO_CLIENT_SECRET= ASGARDEO_BASE_URL=https://api.asgardeo.io/t/ CHOREO_CONSUMER_KEY= CHOREO_ORGANIZATION= CHOREO_TOKEN_ENDPOINT= CHOREO_API_ENDPOINT= ``` -------------------------------- ### Get OIDC Service Endpoints Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md Retrieves OIDC endpoints from the .well-known endpoint. Use this to dynamically fetch configuration details for OIDC flows. ```TypeScript getOIDCServiceEndpoints(): Promise ``` ```TypeScript import { useAuthContext } from "@asgardeo/auth-react"; const App = () => { const { getOIDCServiceEndpoints } = useAuthContext(); useEffect(() => { getOIDCServiceEndpoints().then((endpoints) => { //console.log(endpoints); }).catch((error) => { //console.log(error) }); }, []); } ``` -------------------------------- ### Get ID Token Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md Retrieves the ID token as a string. This token contains information about the user authentication event. Use getDecodedIDToken() to access the decoded payload. ```TypeScript getIDToken(): Promise ``` ```TypeScript import { useAuthContext } from "@asgardeo/auth-react"; const App = () => { const { getIDToken } = useAuthContext(); useEffect(() => { getIDToken().then((idToken) => { //console.log(idToken); }).catch((error) => { //console.log(error); }) }, []); . . . ``` -------------------------------- ### Get Basic User Info Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md Retrieves basic authenticated user information from the ID token. Use this to access common user attributes. Ensure the user is authenticated before calling. ```TypeScript getBasicUserInfo(): Promise; ``` ```TypeScript import { useAuthContext } from "@asgardeo/auth-react"; const App = () => { const { getBasicUserInfo } = useAuthContext(); useEffect(() => { getBasicUserInfo().then((response) => { //console.log(response); }).catch((error) => { //console.error(error); }); }, []); . . . ``` -------------------------------- ### Clone the Repository Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/HACKTOBERFEST.md Clone the Asgardeo React SDK repository to your local machine to begin contributing. ```bash git clone https://github.com/your-username/asgardeo-auth-react-sdk.git cd asgardeo-auth-react-sdk ``` -------------------------------- ### Initiate Authentication with signIn Source: https://context7.com/asgardeo/asgardeo-auth-react-sdk/llms.txt Use `signIn` to redirect users to the Asgardeo login page. It supports basic sign-in, sign-in with configuration options like federated IdP hints, and sign-in with custom token request parameters. A callback can be provided for actions upon successful sign-in. ```typescript import React from "react"; import { useAuthContext, SignInConfig, BasicUserInfo } from "@asgardeo/auth-react"; function LoginPage() { const { signIn, state } = useAuthContext(); // Basic sign-in const handleBasicLogin = () => { signIn(); }; // Sign-in with configuration options const handleConfiguredLogin = async () => { const config: SignInConfig = { fidp: "google", // Federated IdP hint (e.g., "google", "facebook") forceInit: false, // Force re-fetch of .well-known endpoints callOnlyOnRedirect: false }; try { const userInfo: BasicUserInfo = await signIn( config, undefined, // authorizationCode (for form_post mode) undefined, // sessionState undefined, // authState (response) => { // Callback on successful sign-in console.log("Signed in:", response); console.log("Username:", response.username); console.log("Email:", response.email); console.log("Display Name:", response.displayName); } ); console.log("User authenticated:", userInfo); } catch (error) { console.error("Sign-in failed:", error); } }; // Sign-in with custom token request parameters const handleLoginWithParams = () => { signIn( {}, undefined, undefined, undefined, undefined, { params: { resource: "https://api.example.com", audience: "my-api" } } ); }; return (

Login

); } ``` -------------------------------- ### Get Access Token - React SDK Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md Use the `getAccessToken` function from the `useAuthContext` hook to retrieve the current access token. This is typically called within a `useEffect` hook to ensure the token is fetched after the component mounts. ```typescript import { useAuthContext } from "@asgardeo/auth-react"; const App = () => { const { getAccessToken } = useAuthAuthContext(); useEffect(() => { getAccessToken().then((accessToken) => { //console.log(accessToken); }).catch((error) => { //console.log(error); }); }, []); . . . } ``` -------------------------------- ### Configure and Wrap Root Component with AuthProvider Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/README.md Wrap your application's root component with AuthProvider and provide the necessary configuration parameters. Ensure the configuration includes your application's client ID, redirect URLs, and base URL for Asgardeo. ```typescript import React from "react"; import { AuthProvider } from "@asgardeo/auth-react"; const config = { signInRedirectURL: "https://localhost:3000/sign-in", signOutRedirectURL: "https://localhost:3000/dashboard", clientID: "", baseUrl: "https://api.asgardeo.io/t/", scope: [ "openid","profile" ] }; export const MyApp = (): ReactElement => { return ( ) } ``` -------------------------------- ### Get Access Token Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md Retrieves the access token as a string, used for making requests to resource servers. This method only resolves successfully if the storage type is set to sessionStorage or localStorage; it will throw an error if webWorker is used. ```TypeScript getAccessToken(): Promise; ``` -------------------------------- ### Implement Login Button Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/README.md Use the `signIn()` method from `useAuthContext` to create a login button. Clicking this button initiates the Asgardeo login flow. ```TypeScript ``` -------------------------------- ### Get Decoded ID Token Payload Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md Returns a promise that resolves with the decoded payload of the JWT ID token. This method is only successful if the storage type is set to sessionStorage or localStorage; it will throw an error if webWorker is used. ```TypeScript getDecodedIDToken(): Promise ``` ```TypeScript import { useAuthContext } from "@asgardeo/auth-react"; const App = () => { const { getDecodedIDToken } = useAuthContext(); useEffect(() => { getDecodedIDToken().then((decodedIdToken) => { //console.log(decodedIdToken); }).catch((error) => { //console.log(error); }) }, []); . . . ``` -------------------------------- ### Configure SDK with Client ID and Base URL Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/samples/asgardeo-react-app/README.md Update the src/config.json file with your registered application's client ID and base URL. Ensure redirect URLs and scopes are correctly set. ```json { "clientID": "", "baseUrl": "https://api.asgardeo.io/t/", "signInRedirectURL": "https://localhost:3000", "signOutRedirectURL": "https://localhost:3000", "scope": ["profile"] } ``` -------------------------------- ### SDK Configuration Parameters Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md This section details the parameters used for configuring the Asgardeo Auth React SDK. ```APIDOC ## SDK Configuration Parameters ### Description This section details the parameters used for configuring the Asgardeo Auth React SDK. ### Parameters #### Request Body - **responseMode** (ResponseMode) - Optional - Specifies the response mode. The value can either be `query` or `form_post`. - **scope** (string[]) - Optional - Specifies the requested scopes. Defaults to `["openid"]`. - **baseUrl** (string) - Required (If `wellKnownEndpoint` or `endpoints` is not provided) - The origin of the Identity Provider. eg: `https://www.asgardeo.io/t/`. - **endpoints** (OIDCEndpoints) - Optional (Required to provide all endpoints, if `wellKnownEndpoint` or `baseUrl` is not provided) - The OIDC endpoint URLs. The SDK will try to obtain the endpoint URLs using the `.well-known` endpoint. If this fails, the SDK will use these endpoint URLs. If this attribute is not set, then the default endpoint URLs will be used. However, if the `overrideWellEndpointConfig` is set to `true`, then this will override the endpoints obtained from the `.well-known` endpoint. - **wellKnownEndpoint** (string) - Optional - The URL of the `.well-known` endpoint. Defaults to `"/oauth2/token/.well-known/openid-configuration"`. - **overrideWellEndpointConfig** (boolean) - Optional - If this option is set to `true`, then the `endpoints` object will override endpoints obtained from the `.well-known` endpoint. If this is set to `false`, then this will be used as a fallback if the request to the `.well-known` endpoint fails. Defaults to `false`. - **validateIDToken** (boolean) - Optional - Allows you to enable/disable JWT ID token validation after obtaining the ID token. Defaults to `true`. - **clockTolerance** (number) - Optional - Allows you to configure the leeway when validating the id_token. Defaults to `60`. ``` -------------------------------- ### signIn Method Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md The `signIn` method initiates the authentication flow. It can accept various optional arguments to configure the sign-in process, including an authorization code, session state, state parameter, and a callback function for success. It also supports token request configuration. ```APIDOC ## signIn ### Description Initiates the authentication flow. It can accept various optional arguments to configure the sign-in process, including an authorization code, session state, state parameter, and a callback function for success. It also supports token request configuration. ### Method `signIn()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **config?**: `SignInConfig` (optional) - Configuration object for sign-in. Includes `forceInit` and allows appending path parameters. - **authorizationCode?**: `string` (optional) - Authorization code to obtain the token. - **sessionState?**: `string` (optional) - Session state to obtain the token. - **authState?**: `string` (optional) - State parameter for the sign-in process. - **callback?**: `(response: BasicUserInfo) => void` - Callback function executed upon successful sign-in. - **tokenRequestConfig?**: `object` (optional) - Configuration to augment the token request. - **params**: `Record` - Key-value pairs for additional parameters in the token request payload. ### Request Example ```typescript import { useAuthContext } from "@asgardeo/auth-react"; const App = () => { const { signIn } = useAuthContext(); return ( ); } ``` ### Response #### Success Response (200) N/A (The `callback` function handles the response) #### Response Example N/A ``` -------------------------------- ### SDK Configuration Options Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md These options configure the behavior and storage of the Asgardeo Auth React SDK. ```APIDOC ## SDK Configuration Options ### skipRedirectCallback - **Type**: `boolean` - **Optional**: Yes - **Default**: `false` - **Description**: Stops listening to Auth param changes (e.g., `code` & `session_state`) to trigger auto login. ### storage - **Type**: `"sessionStorage"`, `"webWorker"`, `"localStorage"` - **Optional**: Yes - **Default**: `"sessionStorage"` - **Description**: The storage medium where session information (like the access token) is stored. ### resourceServerURLs - **Type**: `string[]` - **Required**: If `storage` is set to `"webWorker"` - **Default**: `[]` - **Description**: URLs of the API endpoints. Required if `storage` is `"webWorker"`. Only calls to endpoints specified in `baseURL` or `resourceServerURLs` will be allowed when using `httpRequest` or `httpRequestAll`. ### requestTimeout - **Type**: `number` - **Optional**: Yes - **Default**: `60000` (seconds) - **Description**: Specifies how long a request to the web worker should wait before timing out. ### disableTrySignInSilently - **Type**: `boolean` - **Optional**: Yes - **Default**: `true` - **Description**: Specifies if the SDK should attempt silent sign-in on mount using an iFrame. ### enableOIDCSessionManagement - **Type**: `boolean` - **Optional**: Yes - **Default**: `false` - **Description**: Enables OIDC Session Management for single logout capabilities. ### periodicTokenRefresh - **Type**: `boolean` - **Optional**: Yes - **Default**: `false` - **Description**: Enables periodic token refresh for the access token. ``` -------------------------------- ### Making HTTP Requests from Non-Components Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md Illustrates how to make HTTP requests from JavaScript or TypeScript logic files that are not React components, by obtaining an instance of `AsgardeoSPAClient`. ```APIDOC ## Making HTTP Requests from Non-Components ### Description This section describes how to make HTTP requests from non-component JavaScript or TypeScript files where React Hooks are not available. It involves getting an instance of `AsgardeoSPAClient` and using its `httpRequestAll` method. ### Usage Import `AsgardeoSPAClient` and get its instance. ### Example ```typescript import { AsgardeoSPAClient } from "@asgardeo/auth-react"; const spaClient = AsgardeoSPAClient.getInstance(); const requestConfigs = [ { headers: { "Accept": "application/json", "Content-Type": "application/scim+json" }, method: "GET", url: "https://api.asgardeo.io/t//oauth2/userinfo" }, { headers: { "Accept": "application/json", "Content-Type": "application/scim+json" }, method: "GET", url: "https://api.asgardeo.io/t//oauth2/jwks" } // ... other request configurations ]; spaClient.httpRequestAll(requestConfigs).then((responses) => { // Process responses responses.forEach((response) => { // console.log(response.data); }); }).catch((error) => { // console.error(error); }); ``` ``` -------------------------------- ### Initialize AuthProvider with Plugin Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md Integrate external plugins like TokenExchangePlugin with AuthProvider by passing an instance of the plugin to the 'plugin' prop. Ensure the plugin is imported correctly. ```typescript import { TokenExchangePlugin } from "@asgardeo/token-exchange-plugin"; export const MyApp = (): ReactElement => { return ( ) } ``` -------------------------------- ### SignIn Configuration Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md Configuration options for the sign-in process. ```APIDOC ### SignInConfig - **fidp** (`string`): Optional. Default: `""`. The `fidp` parameter to redirect directly to an IdP's sign-in page. - **forceInit** (`boolean`): Optional. Default: `false`. Forces obtaining OIDC endpoints from the `.well-known` endpoint. - **callOnlyOnRedirect** (`boolean`): Optional. Default: `false`. Specifies if `signIn` should only be called upon user redirection. - **key** (`string` | `boolean`): Optional. Default: `""`. Any key-value pair to append as path parameters to the authorization URL. ``` -------------------------------- ### signIn - Initiate Authentication Source: https://context7.com/asgardeo/asgardeo-auth-react-sdk/llms.txt Initiates the OIDC authentication flow by redirecting users to the Asgardeo login page. Supports basic sign-in, sign-in with configuration options, and sign-in with custom token request parameters. ```APIDOC ## signIn - Initiate Authentication ### Description The `signIn` method initiates the OIDC authentication flow by redirecting users to the Asgardeo login page. Upon successful authentication, users are redirected back to the `signInRedirectURL` with an authorization code that the SDK automatically exchanges for tokens. ### Method `signIn` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Basic sign-in signIn(); // Sign-in with configuration options signIn({ fidp: "google", forceInit: false, callOnlyOnRedirect: false }); // Sign-in with custom token request parameters signIn( {}, undefined, undefined, undefined, undefined, { params: { resource: "https://api.example.com", audience: "my-api" } } ); ``` ### Response #### Success Response (200) - **userInfo** (BasicUserInfo) - Information about the authenticated user. #### Response Example ```json { "username": "user@example.com", "email": "user@example.com", "displayName": "User Name" } ``` ``` -------------------------------- ### Initiate Sign-In Flow Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md Use the signIn function from the useAuthContext hook to initiate the sign-in process. This is typically triggered by a user action, such as clicking a login button. ```TypeScript import { useAuthContext } from "@asgardeo/auth-react"; const App = () => { const { signIn } = useAuthContext(); . . . return ( . . . ) } ``` -------------------------------- ### Configure Client SDKConfig Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/samples/asgardeo-choreo-react-express/README.md Update SDKConfig in `apps/client/src/config.ts` with your registered app details. Ensure the `clientID` is correctly provided. ```json export const SDKConfig = { clientID: "", signInRedirectURL: "http://localhost:3000", signOutRedirectURL: "http://localhost:3000", baseUrl: "https://api.asgardeo.io/t/", scope: [ "openid","profile" ], disableTrySignInSilently: false, resourceServerURLs: "http://localhost:8080" } export const REACT_APP_API_BASE_URL = "http://localhost:8080"; ``` -------------------------------- ### Initialize AuthProvider with Fallback Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md Use AuthProvider to wrap your application and provide authentication context. The fallback component is rendered while the authentication state is being initialized. ```typescript export const MyApp = (): ReactElement => { return ( Initializing... }> ) } ``` -------------------------------- ### Import AuthProvider Component Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/README.md Import the AuthProvider component from the SDK. This is typically done in your application's root file. ```typescript import { AuthProvider } from "@asgardeo/auth-react"; ``` -------------------------------- ### Import AsgardeoSPAClient from @asgardeo/auth-react Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/README.md Always import APIs from `@asgardeo/auth-react`. Avoid importing from `@asgardeo/auth-spa` directly, even if suggested by IDE auto-imports. ```TypeScript import { AsgardeoSPAClient } from "@asgardeo/auth-react"; ``` -------------------------------- ### Secure Entire Application with SecureApp Source: https://context7.com/asgardeo/asgardeo-auth-react-sdk/llms.txt Wrap your entire application with SecureApp to ensure users are authenticated before rendering. It handles the sign-in flow automatically for unauthenticated users and displays a fallback component during the authentication process. Configure authentication settings via the `config` object. ```typescript import React from "react"; import { AuthProvider, SecureApp } from "@asgardeo/auth-react"; import Dashboard from "./Dashboard"; const config = { signInRedirectURL: "https://localhost:3000", signOutRedirectURL: "https://localhost:3000", clientID: "your-client-id", baseUrl: "https://api.asgardeo.io/t/your-org", scope: ["openid", "profile"] }; // Loading component shown during authentication const LoadingScreen = () => (

Authenticating...

); function App() { const handleSignIn = () => { console.log("User successfully signed in!"); // Navigate to dashboard, fetch initial data, etc. }; // Custom sign-in method (e.g., for form_post response mode) const customSignIn = async () => { // Retrieve authorization code from your backend const authCode = await fetch("/api/auth/code").then(r => r.json()); // Use the signIn method with the retrieved code // This is handled internally by SecureApp }; return ( } onSignIn={handleSignIn} // overrideSignIn={customSignIn} // Optional: custom sign-in logic > ); } export default App; ``` -------------------------------- ### Create a New Branch Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/HACKTOBERFEST.md Create a new branch for each feature or bug fix to keep your work organized. ```bash git checkout -b feature-name ``` -------------------------------- ### Dynamic Configuration Updates Source: https://context7.com/asgardeo/asgardeo-auth-react-sdk/llms.txt Enables modification of SDK configuration settings after initialization. This includes updating redirect URLs, requesting additional scopes, and enabling/disabling features like silent sign-in. ```APIDOC ## updateConfig - Dynamic Configuration Updates ### Description Allows modification of SDK configuration settings after initialization. Useful for dynamically changing settings based on application state. ### Method `updateConfig(newConfig: AuthReactConfig)` ### Parameters #### Request Body - **newConfig** (AuthReactConfig) - An object containing the configuration properties to update. Supported properties include `signOutRedirectURL`, `signInRedirectURL`, `scope`, and `disableTrySignInSilently`. - **signOutRedirectURL** (string) - Optional - The URL to redirect to after sign-out. - **signInRedirectURL** (string) - Optional - The URL to redirect to after sign-in. - **scope** (string[]) - Optional - An array of scopes to request. Updating scopes may require user re-authentication. - **disableTrySignInSilently** (boolean) - Optional - If true, disables silent sign-in attempts. ### Request Example ```typescript updateConfig({ signOutRedirectURL: "https://localhost:3000/goodbye", signInRedirectURL: "https://localhost:3000/welcome" }); updateConfig({ scope: ["openid", "profile", "email", "address", "phone"] }); updateConfig({ disableTrySignInSilently: true }); ``` ### Response This method does not return a value upon successful execution. Errors are typically thrown or handled via console logs in the example. #### Success Response No specific success response body is defined. The operation is considered successful if no errors are thrown. #### Response Example (No response body for success) ``` -------------------------------- ### Securing Routes Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md Provides an overview of the different approaches available for securing routes within a React application using Asgardeo. ```APIDOC ## Securing Routes with Asgardeo ### Description There are 3 approaches you can use to secure routes in your React application with Asgardeo. 1. **SecureApp** 2. **AuthenticatedComponent** 3. **Bring Your Own Router** ``` -------------------------------- ### Use Sign-in and Sign-out Hooks Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md Use the `on` method from `useAuthContext` to subscribe to 'sign-in' and 'sign-out' events. These events trigger callbacks for showing welcome and goodbye messages respectively. Ensure `on` is included in the dependency array of `useEffect`. ```TypeScript import { useAuthContext } from "@asgardeo/auth-react"; enum Hooks { SignIn = "sign-in", SignOut = "sign-out" } const App = () => { const { on } = useAuthContext(); useEffect(() => { on(Hooks.SignIn, () => { //called after signing in. showWelcomeMessage(); }); on(Hooks.SignOut, () => { //called after signing out. showGoodbyeMessage(); }); . . . }, [on]); } ``` -------------------------------- ### httpRequestAll - Sending Multiple Concurrent HTTP Requests Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md The `httpRequestAll` method allows sending multiple, concurrent HTTP requests to Asgardeo or other backend services. This is useful for aggregating results from several endpoints in a single operation. It functions similarly to `axios.all()`. ```APIDOC ## POST /api/batch (Example for httpRequestAll) ### Description Sends multiple, concurrent HTTP requests to different endpoints and returns an array of responses. ### Method POST (or other methods as configured in request objects) ### Endpoint (Varies based on individual request configurations) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **config[]** (HttpRequestConfig[]) - Required - An array of configuration objects for each request. Each object can include: - **attachToken** (boolean) - Optional (default: `true`) - Whether to attach the authentication token. - **shouldEncodeToFormData** (boolean) - Optional (default: `false`) - Whether to encode the request body to `FormData`. - Other standard HTTP request properties (method, url, headers, data, etc.). ### Request Example ```typescript import { useAuthContext } from "@asgardeo/auth-react"; const App = () => { const { httpRequestAll } = useAuthContext(); const requests = [ { method: "GET", url: "https://api.asgardeo.io/t//scim2/me", headers: { "Accept": "application/json" } }, { method: "POST", url: "https://api.example.com/data", data: { key: "value" }, headers: { "Content-Type": "application/json" }, attachToken: false // Example: not attaching token for this request } ]; useEffect(() => { httpRequestAll(requests) .then((responses) => { // responses is an array of results in the same order as the requests array // console.log(responses[0]); // Response from the first request // console.log(responses[1]); // Response from the second request }) .catch((error) => { // If any request fails, the entire promise rejects. // console.error(error); }); }, []) // ... other component logic } ``` ### Response #### Success Response (200) - **responses[]** (Promise[]) - An array of responses, where each response corresponds to the request configuration in the input array, in the same order. #### Response Example ```json { "example": "[response1, response2, ...]" } ``` #### Error Handling If any of the individual requests within `httpRequestAll` fail, the entire `Promise` will be rejected, and no response will be returned, even if other requests were successful. ``` -------------------------------- ### Retrieve User Info and ID Token Claims with Asgardeo SDK Source: https://context7.com/asgardeo/asgardeo-auth-react-sdk/llms.txt Use `getBasicUserInfo` to fetch essential user details and `getDecodedIDToken` to access all claims within the ID token. This is useful for displaying user profiles and utilizing custom attributes. Ensure the user is authenticated before calling these methods. ```typescript import React, { useEffect, useState } from "react"; import { useAuthContext, BasicUserInfo, DecodedIDTokenPayload } from "@asgardeo/auth-react"; function UserDetails() { const { getBasicUserInfo, getDecodedIDToken, getIDToken, getAccessToken, state } = useAuthContext(); const [userInfo, setUserInfo] = useState(null); const [decodedToken, setDecodedToken] = useState(null); useEffect(() => { if (state.isAuthenticated) { // Get basic user information getBasicUserInfo() .then((info) => { setUserInfo(info); // BasicUserInfo contains: // - email: string // - username: string // - displayName: string // - allowedScopes: string // - tenantDomain: string // - sessionState: string }) .catch((error) => console.error("Failed to get user info:", error)); // Get decoded ID token for additional claims getDecodedIDToken() .then((decoded) => { setDecodedToken(decoded); // DecodedIDTokenPayload contains: // - aud: string | string[] // - sub: string // - iss: string // - email: string // - preferred_username: string // - tenant_domain: string // - ... additional custom claims }) .catch((error) => console.error("Failed to decode token:", error)); // Get raw tokens if needed getIDToken().then((token) => console.log("ID Token (JWT):", token)); getAccessToken().then((token) => console.log("Access Token:", token)); } }, [state.isAuthenticated]); if (!userInfo) return
Loading user info...
; return (

User Profile

Username: {userInfo.username}

Email: {userInfo.email}

Display Name: {userInfo.displayName}

Tenant: {userInfo.tenantDomain}

Allowed Scopes: {userInfo.allowedScopes}

{decodedToken && ( <>

Token Claims

Subject: {decodedToken.sub}

Issuer: {decodedToken.iss}

)}
); } ``` -------------------------------- ### updateConfig Method Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md The `updateConfig` method allows you to update SDK configurations after the initial instantiation. All attributes in the config object are optional. ```APIDOC ## updateConfig ### Description This method can be used to update the configurations passed into the constructor of the [`AuthReactConfig`](#authreactconfig). Please note that every attribute in the config object passed as the argument here is optional. Use this method if you want to update certain attributes after instantiating the class. ### Method `updateConfig(config: Partial>): void` ### Arguments #### config - **config** (`Partial>`) - The config object containing the attributes that can be used to configure the SDK. To learn more about the available attributes, refer to the [`AuthReactConfig`](#authreactconfig) model. ### Request Example ```typescript updateConfig({ signOutRedirectURL: "https://localhost:3000/sign-out" }); ``` ``` -------------------------------- ### Making HTTP Requests within React Components Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md Demonstrates how to use `httpRequest` and `httpRequestAll` from the `useAuthContext` hook to make HTTP requests from within React components or hooks. ```APIDOC ## Making HTTP Requests within React Components ### Description This section explains how to make HTTP requests from within React components or custom hooks using the `useAuthContext` hook. It utilizes the `httpRequest` and `httpRequestAll` methods provided by the hook. ### Usage Import `useAuthContext` and destructure `httpRequest` or `httpRequestAll`. ### Example ```typescript import { useAuthContext } from "@asgardeo/auth-react"; const App = () => { const { httpRequest, httpRequestAll } = useAuthContext(); const requestConfigs = [ { headers: { "Accept": "application/json", "Content-Type": "application/scim+json" }, method: "GET", url: "https://api.asgardeo.io/t//oauth2/userinfo" }, { headers: { "Accept": "application/json", "Content-Type": "application/scim+json" }, method: "GET", url: "https://api.asgardeo.io/t//oauth2/jwks" } // ... other request configurations ]; useEffect(() => { httpRequestAll(requestConfigs).then((responses) => { // Process responses responses.forEach((response) => { // console.log(response.data); }); }).catch((error) => { // console.error(error); }); }, []); // ... rest of the component } ``` ``` -------------------------------- ### Make Multiple HTTP Requests from Non-Components Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md When making HTTP requests from non-component JavaScript or TypeScript files, obtain an instance of `AsgardeoSPAClient` and use its `httpRequestAll` method. This is necessary when React Hooks are not available. ```TypeScript import { AsgardeoSPAClient } from "@asgardeo/auth-react"; const spaClient = AsgardeoSPAClient.getInstance(); const requestConfigs = [ { headers: { "Accept": "application/json", "Content-Type": "application/scim+json" }, method: "GET", url: "https://api.asgardeo.io/t//oauth2/userinfo" }, { headers: { "Accept": "application/json", "Content-Type": "application/scim+json" }, method: "GET", url: "https://api.asgardeo.io/t//oauth2/jwks" }, . . . ]; spaClient.httpRequestAll(requestConfigs).then((responses) => { // responses are returned in the order of the requests. // responses[0] will return response from userinfo endpoint. // responses[1] will return response from jwks endpoint. // responses array can be iterated as follows. responses.forEach((response) => { // console.log(response.data); }); }).catch((error) => { // console.error(error); }); ``` -------------------------------- ### signIn Method Signature Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md The signature for the signIn method, showing optional configuration parameters and callbacks for handling the sign-in process. ```typescript signIn( config?: SignInConfig, authorizationCode?: string, sessionState?: string, authState?: string, callback?: (response: BasicUserInfo) => void, tokenRequestConfig?: { params: Record } ); ``` -------------------------------- ### Storage Mechanisms Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md Asgardeo supports storing session information, including access tokens, in Session Storage, Web Worker, or Local Storage. The chosen mechanism can be configured during SDK initialization. ```APIDOC ## Storage Asgardeo allows the session information including the access token to be stored in three different places, namely, 1. [Session storage](#session-storage) 2. [Web worker](#web-worker) 3. [Local storage](#local-storage) The storage mechanism can be defined in the configuration provided to the `` as follows. ```json { "clientID": "", "baseUrl": "https://api.asgardeo.io/t/", "signInRedirectURL": "https://localhost:3000/sign-in", "signOutRedirectURL": "https://localhost:3000/sign-out", "scope": ["openid", "profile"], "storage": "sessionStorage" } ``` ### Session Storage The token is stored in the session of the browser via Javascript. The tokens can be seen when inspected via the browser console. The token stored are only available per tab. Changes made are saved and available for the current page in that tab until it is closed. Once it is closed, the stored data is deleted. ``` -------------------------------- ### Configure Auto Sign-In Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md Set disableAutoSignIn to false in the Asgardeo SDK configuration to enable automatic sign-in when an active session is detected. This feature relies on local storage parameters. ```JSON { ... disableAutoSignIn: false } ``` -------------------------------- ### Declare @asgardeo/auth-react Dependency Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/README.md Ensure that `@asgardeo/auth-react` is the only Asgardeo SDK listed in your application's dependencies within `package.json`. ```JSON // In package.json dependencies: { "@asgardeo/auth-react": "^2.0.0" } ``` -------------------------------- ### Secure React App with SecureApp Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/API.md Wrap your entire React application with SecureApp to automatically handle sign-in flows for unauthenticated users. Use the fallback prop for loading states and onSignIn/overrideSignIn for custom callbacks. ```typescript } onSignIn={ onSignInFunction } overrideSignIn={ overrideSignInFunction } > ``` ```typescript import { SecureApp } from "@asgardeo/auth-react"; const App = () => { return ( } onSignIn={ functionToFireOnSignIn } overrideSignIn={ customSignInMethod} > ); } ``` -------------------------------- ### Show Authenticated User's Information in React Source: https://github.com/asgardeo/asgardeo-auth-react-sdk/blob/main/README.md Demonstrates how to use the `useAuthContext` hook to display authenticated user information and provide login/logout functionality. Ensure the `useAuthContext` is available in the component's scope. ```typescript import React from "react"; import { useAuthContext } from "@asgardeo/auth-react"; function App() { const { state, signIn, signOut } = useAuthContext(); return (
{ state.isAuthenticated ? (
  • {state.username}
) : }
); } export default App; ```