diff --git a/README.md b/README.md index a8dc424..18c06bf 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,43 @@ An **optional** [Open API specification](https://swagger.io/specification/) obje #### **defaultErrorHandler** `(error:OrderCloudError) => void` An **optional** callback function for globally handling OrderCloud errors in your application. Useful for wiring up toast-like feedback. +#### **openIdConnect** `object` +An **optional** object containing configuration for single-sign-on via [OpenID Connect](https://ordercloud.io/knowledge-base/sso-via-openid-connect). + +### **openIdConnect** `boolean` +Set to `true` to activate single-sign-on via OpenIDConnect in your application. If `false`, all OIDC logic (such as login redirects and token handling) will be disabled, even if configs are defined. + +#### **openIdConnect.configs** `{id: string, roles?: string[], clientId: string}[]` +An array of OpenID Connect configuration objects. Each defines the settings required to authenticate against a specific identity provider. At least one configuration must be provided. + +#### **openIdConnect.configs.[i].id** `string` +The ID of the [OpenID connect configuration](https://ordercloud.io/api-reference/authentication-and-authorization/open-id-connects/create) that should be targeted for authentication + +#### **openIdConnect.configs.[i].roles** `string` +An **optional** array of roles that will be requested when authenticating. If excluded, the token generated will contain any roles assigned to the user. Unless you have a specific reason for limiting roles, we recommend omitting this option. + +#### **openIdConnect.configs.[i].clientId** `string` +An **optional** OrderCloud clientId to authenticate against. By default, will use `clientId` at the root of the provider settings. + +#### **openIdConnect.configs.[i].appStartPath** `string` +An **optional** path to redirect the user to after returning from the identity provider. See [here](https://ordercloud.io/knowledge-base/sso-via-openid-connect#deep-linking) for more information + +#### **openIdConnect.configs.[i].customParams** `string` +**optional** query parameters passed along to the `AuthorizationEndpoint`. See [here](https://ordercloud.io/knowledge-base/sso-via-openid-connect) for more information + +#### **openIdConnect.autoRedirect** `boolean` +True will automatically redirect the user to the first openIdConnect config stored if the token is expired, or invalid. This is a simplified use case. For more control, or when you need to handle multiple identity providers set this to false and handle redirect on your own by calling `loginWithOpenIdConnect` + +### **openIdConnect.accessTokenQueryParamName** `string` +Query parameter name where the OrderCloud access token is stored after login. For example, if [AppStartUrl](https://ordercloud.io/api-reference/authentication-and-authorization/open-id-connects/create) is `https://my-application.com/login?token={0}`, use `token` + +### **openIdConnect.refreshTokenQueryParamName** +The **optional** query parameter name for the refresh token after login. Example: if [AppStartUrl](https://ordercloud.io/api-reference/authentication-and-authorization/open-id-connects/create) is `https://my-application.com/login?token={0}&refresh={3}`, use `refresh` + + +### **openIdConnect.idpAccessTokenQueryParamName** +The **optional** query parameter name for the identity provider access token after login. Example: if [AppStartUrl](https://ordercloud.io/api-reference/authentication-and-authorization/open-id-connects/create) is `https://my-application.com/login?token={0}&idptoken={1}`, use `idptoken` + ## `useOrderCloudContext()` hook This hook returns the OrderCloud context that the OrderCloudProvider sets up based on your provided options. If anonymous authentication is allowed the OrderCloud context will automatically be in an authenticated state on first page load (shortly after the first React lifecycle). @@ -53,6 +90,9 @@ When true, the currently active OrderCloud access token is a _registered_ user ( #### **login**: `(username:string, password:string, rememberMe:boolean) => Promise` An asyncrhonous callback method for building a login form for your application. When **rememberMe** is set to `true`, the `OrderCloudProvider` will attempt to store and use the `refresh_token` as long as it is valid. It is not necessary to do anything with the `AccessToken` response as this method will take care of managing the active token and authentication state for you. +### **loginWithOpenIdConnect**: `(openIdConnectId: string, options?: { appStartPath?: string; customParams?: string; }) => void +A method for manually redirecting a user to the identity provider login page defined by the openIdConnectId. To use this method you must define the relevent `openIdConnect` properties + #### **logout**: `() => void` A callback for logging out a registered user from your application. This will also clear the Tanstack query client cache for OrderCloud API calls, forcing any actively used queries to refetch once anonymous auth takes over again or the user logs back in. diff --git a/package-lock.json b/package-lock.json index d279a20..a80b37c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -38,7 +38,8 @@ "@hookform/resolvers": "^3.3.4", "@tanstack/react-query": "^5.62.2", "@tanstack/react-table": "^8.20.5", - "ordercloud-javascript-sdk": "^10.0.0", + "axios": "^1.1.3", + "ordercloud-javascript-sdk": "^11.1.0", "react": "^18.3.1", "react-dom": "^18.3.1", "react-hook-form": "^7.53.2" @@ -4571,9 +4572,9 @@ } }, "node_modules/ordercloud-javascript-sdk": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/ordercloud-javascript-sdk/-/ordercloud-javascript-sdk-10.0.0.tgz", - "integrity": "sha512-wLubfNHSprVb7bLJUq3f6oVy3j3JnBJd2qFpt0y4fyTW/fdwpKOI/Zna/qrh3e0l11a01NknoCdSgtaV/EM1vA==", + "version": "11.1.1", + "resolved": "https://registry.npmjs.org/ordercloud-javascript-sdk/-/ordercloud-javascript-sdk-11.1.1.tgz", + "integrity": "sha512-wV+wN6h+sZwudOTDyugD3SiECnxP1NslAD93frOWxVEYmwNCWrjMdiCFZQEmd0Y6Fz0C+t4vPfdTbrpvuAvemQ==", "license": "MIT", "peer": true, "engines": { diff --git a/package.json b/package.json index 6b7b80e..562c30b 100644 --- a/package.json +++ b/package.json @@ -62,7 +62,8 @@ "@hookform/resolvers": "^3.3.4", "@tanstack/react-query": "^5.62.2", "@tanstack/react-table": "^8.20.5", - "ordercloud-javascript-sdk": "^10.0.0", + "axios": "^1.1.3", + "ordercloud-javascript-sdk": "^11.1.0", "react": "^18.3.1", "react-dom": "^18.3.1", "react-hook-form": "^7.53.2" diff --git a/src/context.ts b/src/context.ts index f2e6fba..ead2731 100644 --- a/src/context.ts +++ b/src/context.ts @@ -9,6 +9,13 @@ const INITIAL_ORDERCLOUD_CONTEXT: IOrderCloudContext = { login: async (username: string, password: string, rememberMe?: boolean) => { return Promise.reject({username, password, rememberMe}) }, + loginWithOpenIdConnect: ( + openIdConnectId: string + ) => { + throw new Error( + `loginWithOpenIdConnect is not implemented. ${openIdConnectId}` + ); + }, setToken: async (accessToken: string ) => { return Promise.reject({accessToken}) }, diff --git a/src/hooks/useOnceAtATime.ts b/src/hooks/useOnceAtATime.ts new file mode 100644 index 0000000..45d31e0 --- /dev/null +++ b/src/hooks/useOnceAtATime.ts @@ -0,0 +1,42 @@ +import { useRef, useCallback } from 'react'; + +/** + * useOnceAtATime + * + * A React hook that ensures an async function is only executed once at a time. + * While the function is in-flight, all subsequent calls return the same Promise. + * Once the function resolves or rejects, it can be called again. + * + * Useful for deduplicating concurrent requests (e.g. token validation, lazy loading). + * + * @template TArgs - Argument types of the async function + * @template TResult - Return type of the async function + * + * @param fn - The async function to guard + * @returns An object with: + * - run: the deduplicated function + * - isRunning: boolean indicating whether the function is currently executing + */ +export function useOnceAtATime( + fn: (...args: TArgs) => Promise +) { + const inFlightRef = useRef | null>(null); + + const run = useCallback((...args: TArgs): Promise => { + if (inFlightRef.current) return inFlightRef.current; + + inFlightRef.current = (async () => { + try { + return await fn(...args); + } finally { + inFlightRef.current = null; // allow future calls + } + })(); + + return inFlightRef.current; + }, [fn]); + + const isRunning = !!inFlightRef.current; + + return { run, isRunning }; +} \ No newline at end of file diff --git a/src/models/IOpenIdConnectSettings.ts b/src/models/IOpenIdConnectSettings.ts new file mode 100644 index 0000000..8b8dc06 --- /dev/null +++ b/src/models/IOpenIdConnectSettings.ts @@ -0,0 +1,89 @@ +export interface IOpenIdConnectSettings +{ + /** + * Enables or disables OpenID Connect authentication. + * + * Set to `true` to activate OIDC support in your application. If `false`, all OIDC logic + * (such as login redirects and token handling) will be disabled, even if configs are defined. + */ + enabled: boolean + /** + * An array of OpenID Connect configuration objects. + * Each defines the settings required to authenticate against a specific identity provider. + * At least one configuration must be provided. + */ + configs: IOpenIdConnectConfig[] + /** + * True will automatically redirect the user to the + * first openIdConnect config stored if the token is expired, or invalid. + * This is a simplified use case. For more control, or when you need to + * handle multiple identity providers set this to false and handle redirect on your + * own by calling `loginWithOpenIdConnect` + */ + autoRedirect?: boolean + /** + * The name of the query parameter under which the ordercloud access token will be stored under after successful login. + * This will vary based on your [OpenIdConnect.AppStartUrl](https://ordercloud.io/api-reference/authentication-and-authorization/open-id-connects/create). + * For example if your `AppStartUrl` is `https://my-buyer-application.com/login?token={0}` then the value should be `token` + */ + accessTokenQueryParamName: string + /** + * The **optional** name of the query parameter under which the ordercloud refresh token will be stored + * under after successful login. This will vary based on your [OpenIdConnect.AppStartUrl](https://ordercloud.io/api-reference/authentication-and-authorization/open-id-connects/create). + * For example if your `AppStartUrl` is `https://my-buyer-application.com/login?token={0}&refresh={3}` then the value should be `refresh` + */ + refreshTokenQueryParamName?: string + /** + * The **optional** name of the query parameter under which the idp access token will be stored + * under after successful login. This will vary based on your [OpenIdConnect.AppStartUrl](https://ordercloud.io/api-reference/authentication-and-authorization/open-id-connects/create). + * For example if your `AppStartUrl` is `https://my-buyer-application.com/login?token={0}&idptoken={1}` then the value should be `idptoken` + */ + idpAccessTokenQueryParamName?: string + /** + * An **optional** path to redirect the user to after returning from the identity provider. + * See [here](https://ordercloud.io/knowledge-base/sso-via-openid-connect#deep-linking) for more information + * This global setting will be used if not overridden by the `appStartPath` in the individual OpenID Connect configurations. + * Call `setAppStartPath()` to change this value at runtime. + */ + appStartPath?: string + /** + * **optional** query parameters passed along to the `AuthorizationEndpoint`. + * See [here](https://ordercloud.io/knowledge-base/sso-via-openid-connect) for more information + * This global setting will be used if not overridden by the `customParams` in the individual OpenID Connect configurations. + * Call `setCustomParams()` to change this value at runtime. + */ + customParams?: string +} + +export interface IOpenIdConnectConfig +{ + /** + * The ID of the [OpenID connect configuration](https://ordercloud.io/api-reference/authentication-and-authorization/open-id-connects/create) + * that should be targeted for authentication + */ + id: string + /** + * An **optional** array of roles that will be requested when authenticating. + * If excluded, the token generated will contain any roles assigned to the user. + * Unless you have a specific reason for limiting roles, we recommend omitting this option. + */ + roles?: string[] + /** + * An **optional** OrderCloud clientId to authenticate against. + * By default, will use `clientId` at the root of the provider settings. + */ + clientId?: string + /** + * An **optional** path to redirect the user to after returning from the identity provider. + * See [here](https://ordercloud.io/knowledge-base/sso-via-openid-connect#deep-linking) for more information + * call `setAppStartPath(openIdConnectConfigId)` to change this value at runtime. + */ + appStartPath?: string + + /** + * **optional** query parameters passed along to the `AuthorizationEndpoint`. + * See [here](https://ordercloud.io/knowledge-base/sso-via-openid-connect) for more information + * call `setCustomParams(openIdConnectConfigId)` to change this value at runtime. + */ + customParams?: string +} \ No newline at end of file diff --git a/src/models/IOrderCloudContext.ts b/src/models/IOrderCloudContext.ts index ece83f1..d6ce0a9 100644 --- a/src/models/IOrderCloudContext.ts +++ b/src/models/IOrderCloudContext.ts @@ -1,4 +1,8 @@ -import { AccessToken, ApiRole, OrderCloudError } from "ordercloud-javascript-sdk"; +import { + AccessToken, + ApiRole, + OrderCloudError, +} from "ordercloud-javascript-sdk"; import { IOrderCloudErrorContext } from "./IOrderCloudErrorContext"; import { OpenAPIV3 } from "openapi-types"; @@ -21,15 +25,29 @@ export interface IOrderCloudContext { /** * authenticates using the configured client ID and username / password */ - login: (username:string, password:string, rememberMe?:boolean) => Promise; + login: ( + username: string, + password: string, + rememberMe?: boolean + ) => Promise; + /** + * authenticates using the configured OpenID Connect settings + */ + loginWithOpenIdConnect: ( + openIdConnectId: string, + options?: { + appStartPath?: string; + customParams?: string; + } + ) => void; /** * authenticates using the provided OrderCloud access token */ - setToken: (accessToken: string ) => void; + setToken: (accessToken: string) => void; /** * Signifies when authorization is in a loading state */ - authLoading: boolean + authLoading: boolean; /** * If anonymous, this will retrieve a new anon token, useful for anonymous @@ -43,9 +61,13 @@ export interface IOrderCloudContext { scope?: ApiRole[]; customScope?: string[]; allowAnonymous: boolean; - defaultErrorHandler?: (error:OrderCloudError, context:IOrderCloudErrorContext) => void; + defaultErrorHandler?: ( + error: OrderCloudError, + context: IOrderCloudErrorContext + ) => void; token?: string; + idpToken?: string; xpSchemas?: OpenAPIV3.SchemaObject; autoApplyPromotions?: boolean; - currencyDefaults: { currencyCode: string, language: string } -} \ No newline at end of file + currencyDefaults: { currencyCode: string; language: string }; +} diff --git a/src/models/IOrderCloudProvider.ts b/src/models/IOrderCloudProvider.ts index ae1d929..c3512c9 100644 --- a/src/models/IOrderCloudProvider.ts +++ b/src/models/IOrderCloudProvider.ts @@ -1,6 +1,7 @@ import { ApiRole, OrderCloudError, SdkConfiguration } from "ordercloud-javascript-sdk"; import { IOrderCloudContext } from "./IOrderCloudContext"; import { OpenAPIV3 } from "openapi-types"; +import { IOpenIdConnectSettings } from "./IOpenIdConnectSettings"; export interface IOrderCloudProvider { baseApiUrl: string; @@ -8,6 +9,7 @@ export interface IOrderCloudProvider { scope?: ApiRole[]; customScope?: string[]; allowAnonymous: boolean; + openIdConnect?: IOpenIdConnectSettings; xpSchemas?: OpenAPIV3.SchemaObject; autoApplyPromotions?: boolean, configurationOverrides?: Omit diff --git a/src/models/index.ts b/src/models/index.ts index 27805ae..c362f6d 100644 --- a/src/models/index.ts +++ b/src/models/index.ts @@ -2,10 +2,13 @@ import { IOrderCloudOperationObject } from "./IOrderCloudOperationObject"; import { IOrderCloudContext } from "./IOrderCloudContext"; import { IOrderCloudErrorContext } from "./IOrderCloudErrorContext"; import { IOrderCloudProvider } from "./IOrderCloudProvider"; +import { IOpenIdConnectSettings, IOpenIdConnectConfig } from "./IOpenIdConnectSettings"; export type { IOrderCloudContext, IOrderCloudErrorContext, IOrderCloudProvider, - IOrderCloudOperationObject + IOrderCloudOperationObject, + IOpenIdConnectSettings, + IOpenIdConnectConfig } \ No newline at end of file diff --git a/src/provider.tsx b/src/provider.tsx index fcee7fd..d5cec3e 100644 --- a/src/provider.tsx +++ b/src/provider.tsx @@ -18,6 +18,8 @@ import { IOrderCloudProvider } from "./models/IOrderCloudProvider"; import { asyncStoragePersister, queryClient } from "./query"; import { isAnonToken } from "./utils"; import axios from "axios"; +import { IOpenIdConnectConfig } from "./models/IOpenIdConnectSettings"; +import { useOnceAtATime } from "./hooks/useOnceAtATime"; let interceptorSetup = false; const OrderCloudProvider: FC> = ({ @@ -27,6 +29,7 @@ const OrderCloudProvider: FC> = ({ scope, customScope, allowAnonymous, + openIdConnect, xpSchemas, autoApplyPromotions, configurationOverrides, @@ -53,13 +56,31 @@ const OrderCloudProvider: FC> = ({ const [token, setToken] = useState(); const [authLoading, setAuthLoading] = useState(true); + if (openIdConnect?.enabled) { + if ( + !openIdConnect || + !openIdConnect.configs || + openIdConnect.configs.length === 0 + ) { + throw new Error( + "OpenID Connect is enabled, but no configurations were provided." + ); + } + + if (!openIdConnect.accessTokenQueryParamName) { + throw new Error( + "OpenID Connect is enabled, but accessTokenQueryParamName is missing." + ); + } + } + const handleLogout = useCallback(() => { queryClient.clear(); + Tokens.RemoveAccessToken(); + Tokens.RemoveRefreshToken(); setIsAuthenticated(false); setIsLoggedIn(false); setToken(undefined); - Tokens.RemoveAccessToken(); - Tokens.RemoveRefreshToken(); setAuthLoading(false); }, []); @@ -92,46 +113,174 @@ const OrderCloudProvider: FC> = ({ [clientId, scope, customScope] ); - const verifyToken = useCallback( - async (accessToken?: string) => { - setAuthLoading(true); - if (accessToken) { - Tokens.SetAccessToken(accessToken); - Tokens.RemoveRefreshToken(); + const handleLoginWithOpenIdConnect = useCallback( + ( + openIdConnectId: string, + options?: { + appStartPath?: string; + customParams?: string; } - const token = await Tokens.GetValidToken(); - - if (token) { - const isAnon = isAnonToken(token); - if (isAnon && !allowAnonymous) { - handleLogout(); - return; - } - setIsAuthenticated(true); - setToken(token); - if (!isAnon) setIsLoggedIn(true); - setAuthLoading(false); - return; + ) => { + const config = openIdConnect?.configs.find( + (c) => c.id === openIdConnectId + ); + if (!config) { + throw new Error( + `OpenID Connect configuration with id ${openIdConnectId} not found.` + ); } + handleOpenIdConnectRedirect( + config, + options?.appStartPath, + options?.customParams + ); + }, + [] + ); - if (!allowAnonymous) { - setAuthLoading(false); - return; + const handleOpenIdConnectAutoRedirect = useCallback(() => { + const config = openIdConnect?.configs[0] as IOpenIdConnectConfig + handleOpenIdConnectRedirect(config); + }, [openIdConnect]); + + const handleOpenIdConnectRedirect = useCallback( + ( + config: IOpenIdConnectConfig, + overrideAppStartPath?: string, + overrideCustomParams?: string + ) => { + const appRoles = [...(scope || []), ...(customScope || [])]; + let redirectUrl = + `${baseApiUrl}/ocrplogin?id=${config.id}` + + `&cid=${config.clientId || clientId}`; + + if (config.roles) { + redirectUrl += `&roles=${encodeURIComponent(config.roles.join(" "))}`; + } else if (appRoles.length > 0) { + redirectUrl += `&roles=${encodeURIComponent(appRoles.join(" "))}`; } - const { access_token, refresh_token } = await Auth.Anonymous( - clientId, - scope, - customScope - ); + if (overrideAppStartPath) { + redirectUrl += `&appstartpath=${encodeURIComponent( + overrideAppStartPath + )}`; + } else if (config.appStartPath) { + redirectUrl += `&appstartpath=${encodeURIComponent( + config.appStartPath + )}`; + } else if (openIdConnect?.appStartPath) { + redirectUrl += `&appstartpath=${encodeURIComponent( + openIdConnect.appStartPath + )}`; + } - Tokens.SetAccessToken(access_token); - Tokens.SetRefreshToken(refresh_token); - setIsAuthenticated(true); - setIsLoggedIn(false); - setAuthLoading(false); + if (overrideCustomParams) { + redirectUrl += `&customParams=${encodeURIComponent( + overrideCustomParams + )}`; + } else if (config.customParams) { + redirectUrl += `&customParams=${encodeURIComponent( + config.customParams + )}`; + } else if (openIdConnect?.customParams) { + redirectUrl += `&customParams=${encodeURIComponent( + openIdConnect.customParams + )}`; + } + window.location.assign(redirectUrl); }, - [allowAnonymous, clientId, scope, customScope, handleLogout] + [openIdConnect, clientId, scope, customScope, baseApiUrl] + ); + + const { run: verifyToken } = useOnceAtATime( + useCallback( + async (accessToken?: string) => { + setAuthLoading(true); + + if (openIdConnect?.enabled && openIdConnect.accessTokenQueryParamName) { + // User is being redirected to app after completing single-sign in flow + const urlParams = new URLSearchParams(window.location.search); + const accessTokenFromUrl = urlParams.get( + openIdConnect.accessTokenQueryParamName + ); + const refreshTokenFromUrl = openIdConnect.refreshTokenQueryParamName + ? urlParams.get(openIdConnect.refreshTokenQueryParamName) + : null; + const idpAccessTokenFromUrl = + openIdConnect.idpAccessTokenQueryParamName + ? urlParams.get(openIdConnect.idpAccessTokenQueryParamName) + : null; + + if (accessTokenFromUrl) { + Tokens.SetAccessToken(accessTokenFromUrl); + if (refreshTokenFromUrl) + Tokens.SetRefreshToken(refreshTokenFromUrl); + if (idpAccessTokenFromUrl) + Tokens.SetIdpAccessToken(idpAccessTokenFromUrl); + + // Remove only token-related params + urlParams.delete(openIdConnect.accessTokenQueryParamName); + if (openIdConnect.refreshTokenQueryParamName) + urlParams.delete(openIdConnect.refreshTokenQueryParamName); + if (openIdConnect.idpAccessTokenQueryParamName) + urlParams.delete(openIdConnect.idpAccessTokenQueryParamName); + + const url = new URL(window.location.href); + url.search = urlParams.toString(); + window.history.replaceState({}, document.title, url.toString()); + + setToken(accessTokenFromUrl); + setIsAuthenticated(true); + setIsLoggedIn(true); + setAuthLoading(false); + return; + } + } + + if (accessToken) { + Tokens.SetAccessToken(accessToken); + Tokens.RemoveRefreshToken(); + } + + const token = await Tokens.GetValidToken(); + + if (token) { + const isAnon = isAnonToken(token); + if (isAnon && !allowAnonymous) { + handleLogout(); + return; + } + + setIsAuthenticated(true); + setToken(token); + if (!isAnon) setIsLoggedIn(true); + setAuthLoading(false); + return; + } + + if (openIdConnect?.enabled && openIdConnect?.autoRedirect) { + return handleOpenIdConnectAutoRedirect(); + } + + if (!allowAnonymous) { + setAuthLoading(false); + return; + } + + const { access_token, refresh_token } = await Auth.Anonymous( + clientId, + scope, + customScope + ); + + Tokens.SetAccessToken(access_token); + Tokens.SetRefreshToken(refresh_token); + setIsAuthenticated(true); + setIsLoggedIn(false); + setAuthLoading(false); + }, + [allowAnonymous, clientId, scope, customScope, handleLogout] + ) ); const newAnonSession = useCallback(async () => { @@ -176,7 +325,6 @@ const OrderCloudProvider: FC> = ({ return Promise.reject(error); } ); - } else { interceptorSetup = true; } @@ -209,6 +357,7 @@ const OrderCloudProvider: FC> = ({ currencyDefaults, logout: handleLogout, login: handleLogin, + loginWithOpenIdConnect: handleLoginWithOpenIdConnect, setToken: handleProvidedToken, defaultErrorHandler, }; @@ -228,6 +377,7 @@ const OrderCloudProvider: FC> = ({ currencyDefaults, handleLogout, handleLogin, + handleLoginWithOpenIdConnect, handleProvidedToken, defaultErrorHandler, ]);