Broadleaf Microservices
  • v1.0.0-latest-prod

Auth Client

The AuthClient handles operations against the Auth Service APIs.

Properties

Name Type Required Description

baseURL

string

The base URL of the authorization server.

protected

clientId

string

The client ID.

protected

accountId

string

The current customer account ID. Usually only used in B2B contexts.

protected

agent

AxiosInstance

The agent used for making HTTP requests.

protected

redirectUri

string

The default redirect URI used for login redirect flow.

protected

scope

string

The default scope used for authorization requests. If #useRefreshTokens is true, then OFFLINE_ACCESS will automatically be included

protected

silentRedirectUri

string

The default redirect URI used for the silent authentication flow.

protected

transactionManager

TransactionManager

Manages the authorization transactions. protected

tokenCache

TokenCache

Cache used to hold access tokens.

protected

useRefreshTokens

boolean

Whether to use a refresh token rotation instead of the standard auth code grant flow with silent authentication. See Refresh Token (Rotation) Grant Type docs.

The default is false.

protected

useIFrameAsFallbackForRefreshToken

boolean

Whether to use silent authentication with iframe as a fallback when #useRefreshTokens is true but there is no cached refresh token. This can occur when the user reloads the browser window since the tokens are stored in-memory.

Default is true.

protected

useSessionStorageForTokenCache

boolean

Whether to serialize the in-memory token cache to session storage to allow persistence across page loads.

This is somewhat less secure than leaving the cache in-memory but may be necessary in cross-domain auth contexts, i.e., when the client is served on a different domain from the auth server, because browsers block the cross-domain session cookie. In these cases, the additional risk should be mitigated by also enabling refresh tokens (useRefreshTokens) with refresh token rotation and re-use detection—both supported by Broadleaf out of box when enabled.

Default is false.

protected

useLocalStorageForTokenCache

boolean

Whether to serialize the in-memory token cache to local storage to allow persistence across page loads. This is similar to useSessionStorageForTokenCache but that local storage isn’t cleared when the browser is closed.

Default is false.

protected

enableAutoRedirectToLoginParam

boolean

Determines whether a param indicating that the app should automatically redirect the user to login is enabled. This is used in cases where auto-login from the server is not possible due to needing third-party-cookies, which are blocked in most browsers by default. This param is usually not used unless refresh-token-rotation is also used.

The param’s value is redirectToLogin=true.

Default is false.

protected

Log-In with Redirect

Redirects the user to login by initiating an OAuth2 Authorization Code Grant (optionally) with PKCE flow.

Operation

AuthClient#loginWithRedirect(options);

Parameters

Parameter Type Required? Description

options

LoginRedirectOptions

Configuration options when building the URL for a login request to the authorization server.

Response

Void. This method will cause the browser to redirect to the authorization url.

Example

Example log in with redirect
await authClient.loginWithRedirect(
  { scope: 'USER CUSTOMER_USER' }
);

Handle Redirect Callback

Handles parsing the callback parameters as part of the OAuth2 Authorization Code Grant (optionally) with PKCE flow. This flow is typically first initiated with a call to #loginWithRedirect.

AuthClient#handleRedirectCallback(url);

Parameters

Parameter Type Required? Description

url

string

Browser URL with callback parameters code, state, error, and error_description. Defaults to window.location.href.

Response

The result from a login-with-redirect request. This holds the state that should be validated in the app in the auth code grant flow: LoginRedirectResult. LoginRedirectResult#appState will usually be AuthAppState.

Example

Example handling a login redirect response
const { appState } = await authClient.handleRedirectCallback();

Get Access Token

Gets an access token. If #useRefreshTokens is true, then this will use the refresh token to get a new access token. Else, it will use silent authentication in an iframe.

AuthClient#getAccessToken();

Parameters

Parameter Type Required? Description

options

GetAccessTokenOptions

Options for fetching the access token such as whether to ignore the token cache, an override scope, etc.

Response

The access token string, which will also be cached.

Example

Example getting the new access token
const token = await authClient.getAccessToken();

Check Session

Checks if the user has a session and refresh the session by silently retrieving a token that pre-fills the token cache. This will suppress 'login_required' errors as these are recoverable by asking the user to login.

AuthClient#checkSession();

Parameters

Parameter Type Required? Description

options

GetAccessTokenOptions

Options for fetching the access token such as whether to ignore the token cache, an override scope, etc.

Response

None.

Example

Example checking the session status and
await authClient.checkSession();

Ger User Info

Fetches the user information from the auth server.

AuthClient#getUserInfo();

Parameters

None.

Response

The authenticated user’s info: User.

Example

Example checking the session status and
const user = await authClient.getUserInfo();

Log-Out with Redirect

Clears the authenticated user’s session with the authorization server. Upon a successful logout, redirects to the LogoutRedirectOptions#returnTo location.

AuthClient#logoutWithRedirect();

Parameters

Parameter Type Required? Description

options

LogoutRedirectOptions

The request options including where to redirect to after success. The returnTo option defaults to window.location.origin;

Response

None. This will cause a browser redirection.

Example

Example of log out with redirect
await authClient.logoutWithRedirect({ returnTo: window.location.origin + '/logout-success' });

Change Password with Redirect

Redirects the user to change their password on the authorization server. Upon a successful change password, the user will be redirect back to the application using the provided ChangePasswordRedirectOptions#returnTo URL.

Note, the returnTo location must be a valid redirect URI for the authorized client.

AuthClient#changePasswordWithRedirect();

Parameters

Parameter Type Required? Description

options

ChangePasswordRedirectOptions

The request options including where to redirect to after success. The returnTo option defaults to window.location.origin;

Response

None. This will cause a browser redirection.

Example

Example of change password with redirect
authClient.changePasswordWithRedirect({ returnTo: window.location.origin + '/change-password-success' });

Register with Redirect

Redirects the user to register on the authorization server. Upon a successful registration, the user will be redirect back to the application using the provided RegisterRedirectOptions#returnTo URL.

Note, the returnTo location must be a valid redirect URI for the authorized client.

AuthClient#registerWithRedirect();

Parameters

Parameter Type Required? Description

options

RegisterRedirectOptions

The request options including where to redirect to after success. The returnTo option defaults to window.location.origin;

Response

None. This will cause a browser redirection.

Example

Example of register with redirect
authClient.registerWithRedirect({ returnTo: window.location.origin + '/change-password-success' });

Is Authenticated

Returns whether or not we are able to determine that the user is authenticated. It checks to see if there is a cached token for the default client scope.

AuthClient#isAuthenticated();

Parameters

None.

Response

Boolean for whether the user is authenticated.

Example

Example of checking if the user is authenticated
const isAuthenticated = authClient.isAuthenticated();

Get Session Expiry

Returns the latest known SessionExpiry for the default user scope. If no token is cached, this will return undefined.

AuthClient#getSessionExpiry();

Parameters

Parameter Type Required? Description

options

GetSessionExpiryOptions

Options for configuration the request to get the latest SessionExpiry for the user scope.

Response

The SessionExpiry or undefined if none.

Example

Example of register with redirect
const expiry = authClient.getSessionExpiry();

Get Identity Claims

Returns the identity claims for the latest AccessToken. Uses the scope provided within the GetIdentityClaimsOptions to retrieve a cached token’s IdentityClaims. If no scope is provided, the default scope will be used.

AuthClient#getIdentityClaims();

Parameters

Parameter Type Required? Description

options

GetIdentityClaimsOptions

Configuration options for when building the URL for the request to get the IdentityClaims for an AccessToken.

Response

The IdentityClaims or undefined if none.

Example

Example of getting the user’s identity claims.
const claims = authClient.getIdentityClaims();

Log-In with Credentials (embedded login)

Method to use when logging in from an embedded form instead of redirecting to the auth server for in the Authentication Microservice’s configuration properties. On the backend, broadleaf.auth.login.embedded.enabled (global property) must be true and the AuthorizationServer being submitted to must have embeddedLoginEnabled also set to true.

The request will return a one-time-password token that will be sent to retrieve an access token automatically.

AuthClient#loginWithCredentials(request, options);

Parameters

Parameter Type Required? Description

request

LoginWithCredentialsRequest

Represents a request to log in a user with credentials for an embedded login form as opposed to logging in with a redirect for Universal Login.

options

LoginWithCredentialsOptions

Request options to include.

Response

None. The access retrieved will be cached.

Example

Example of logging a user in with an embedded form
await authClient.loginWithCredentials({ username: 'email@example.com', password: 'password' });

Register with Credentials (embedded registration)

Method to use when registering from an embedded form instead of redirecting to the auth server for Universal Login. On the backend, broadleaf.auth.login.embedded.enabled (global property) must be true and the auth server being submitted to must have embeddedLoginEnabled also set to true.

Note
The responding request may include a session cookie (signed JWT) if auto-login is enabled on the server.
AuthClient#registerWithCredentials(request);

Parameters

Parameter Type Required? Description

request

RegisterWithCredentialsRequest

Represents a request to register a user with credentials for an embedded form as opposed to registering with a redirect for Universal Login.

Response

The new User.

Example

Example of registering a user with an embedded form
const user = await authClient.registerWithCredentials({
  type: 'CUSTOMER',
  fullName: 'First Last',
  username: 'email@example.com',
  email: 'email@example.com',
  password: 'password',
  passwordConfirmation: 'password'
});

Change Password with Credentials (embedded change-password)

Method to use when changing password from an embedded form instead of redirecting to the auth server for Universal Login. On the backend, broadleaf.auth.login.embedded.enabled (global property) must be true and the auth server being submitted to must have embeddedLoginEnabled also set to true.

AuthClient#changePasswordWithCredentials(request);

Parameters

Parameter Type Required? Description

request

ChangePasswordWithCredentialsRequest

Represents a request to change a user’s password for an embedded form as opposed to changing the password with a redirect for Universal Login.

Response

None.

Example

Example of changing a user’s password with an embedded form
const user = await authClient.changePasswordWithCredentials({
  currentPassword: 'password',
  newPassword: 'newPassword',
  newPasswordConfirm: 'newPassword'
});

Method to use when requesting a reset password link from an embedded form instead of redirecting to the auth server for Universal Login. On the backend, broadleaf.auth.login.embedded.enabled (global property) must be true and the auth server being submitted to must have embeddedLoginEnabled also set to true.

AuthClient#requestResetPasswordLinkWithCredentials(request);

Parameters

Parameter Type Required? Description

request

RequestResetPasswordLinkRequest

Represents a request to get a link to reset a user’s password for an embedded form as opposed to doing so with a redirect to Universal Login.

Response

None. An email should be sent on success to the user’s email.

Example

Example of requesting a reset password link for a user with an embedded form
await authClient.requestResetPasswordLinkWithCredentials({ username: 'email@example.com' });

Reset Password with Credentials (embedded reset-password)

Method to use when resetting a password from an embedded form instead of redirecting to the auth server for Universal Login. On the backend, broadleaf.auth.login.embedded.enabled (global property) must be true and the auth server being submitted to must have embeddedLoginEnabled also set to true.

Note
The responding request may include a session cookie if auto-login is enabled on the server.
AuthClient#resetPasswordWithCredentials(request);

Parameters

Parameter Type Required? Description

request

ResetPasswordWithCredentialsRequest

Represents a request to to reset a user’s password for an embedded form as opposed to doing so with a redirect to Universal Login.

Response

None.

Example

Example of resetting a password for a user with an embedded form
await authClient.resetPasswordWithCredentials({
  username: 'email@example.com',
  password: 'newPassword',
  token: 'abc123!@#'
});