Configuring JavaScript apps for OIDC sign-on
PingOne PingOne Advanced Identity Cloud PingAM OIDC-compliant servers JavaScript
You can configure your JavaScript apps to use your authorization server’s UI, or your own web application, for sign-on requests.
When a user attempts to sign on to your app it redirects them to the central sign-on UI. After the user authenticates, the authorization server redirects them back to your application or site.
Changes to authentication journeys or flows on your authorization server are available to all your apps that use the OIDC sign-on method, without the need to rebuild or redistribute the app. Likewise, any rebranding applied to your central sign-on UI is reflected immediately in your client apps.
Your app doesn’t need to access user credentials directly, just the result of the authentication from the server—usually an access token.
To configure an JavaScript app to perform OIDC sign-on, complete each of the following steps:
Before you begin
You need to prepare your server for OIDC sign-on. Select your server from the options below and complete the tasks before proceeding to configure your application.
-
PingOne
-
Advanced Identity Cloud
-
AM
-
PingFederate
This tutorial requires you to configure your PingOne server as follows:
Task 1. Create a demo user
The samples and tutorials in this documentation often require that you have an identity set up so that you can test authentication.
To create a demo user in PingOne, follow these steps:
-
Log in to your PingOne administration console.
-
In the left panel, navigate to Directory > Users.
-
Next to the Users label, click the plus icon ().
PingOne displays the Add User panel.
-
Enter the following details:
-
Given Name =
Demo -
Family Name =
User -
Username =
demo -
Email =
demo.user@example.com -
Population =
Default -
Password =
Ch4ng3it!
-
-
Click Save.
Task 2. Register a public OAuth 2.0 client
To register a public OAuth 2.0 client application in PingOne for use with the Orchestration SDK for JavaScript, follow these steps:
-
Log in to your PingOne administration console.
-
In the left panel, navigate to Applications > Applications.
-
Next to the Applications label, click the plus icon ().
PingOne displays the Add Application panel.
-
In Application Name, enter a name for the profile, for example
sdkPublicClient -
Select OIDC Web App as the Application Type, and then click Save.
-
On the Configuration tab, click the pencil icon ().
-
In Grant Type, select the following:
Authorization CodeRefresh Token -
In Redirect URIs, enter the following:
https://localhost:8443/callback.htmlAlso add any other URLs where you host SDK applications.
Failure to add redirect URLs that exactly match your client app’s values can cause PingOne to display an error message such as
Redirect URI mismatchwhen attempting to end a session by redirecting from the SDK. -
In Token Endpoint Authentication Method, select
None. -
In Signoff URLs, enter the following:
https://localhost:8443Also add any other URLs that redirect users to PingOne to end their session.
Failure to add sign off URLs that exactly match your client app’s values can cause PingOne to display an error message such as
invalid post logout redirect URIwhen attempting to end a session by redirecting from the SDK. -
In CORS Settings, in the drop-down select Allow specific origins, and in the Allowed Origins field, enter the URL where you will be running the sample app.
For example,
https://localhost:8443 -
In the Advanced Settings section, enable Terminate User Session by ID Token.
-
Click Save.
-
-
On the Resources tab, next to Allowed Scopes, click the pencil icon ().
-
In Scopes, select the following values:
emailphoneprofileThe openidscope is selected by default.The result resembles the following:
Figure 1. Adding scopes to an application.
-
-
Optionally, on the Policies tab, click the pencil icon () to select the authentication policies for the application.
Applications that have no authentication policy assignments use the environment’s default authentication policy to authenticate users.
If you have a DaVinci license, you can select PingOne policies or DaVinci Flow policies, but not both. If you do not have a DaVinci license, the page only displays PingOne policies.
To use a PingOne policy:
-
Click Add policies and then select the policies that you want to apply to the application.
-
Click Save.
PingOne applies the policies in the order in which they appear in the list. PingOne evaluates the first policy in the list first. If the requirements are not met, PingOne moves to the next one.
For more information, see Authentication policies for applications.
To use a DaVinci Flow policy:
-
You must clear all PingOne policies. Click Deselect all PingOne Policies.
-
In the confirmation message, click Continue.
-
On the DaVinci Policies tab, select the policies that you want to apply to the application.
-
Click Save.
PingOne applies the first policy in the list.
-
-
Click Save.
-
Enable the OAuth 2.0 client application by using the toggle next to its name:
Figure 2. Enable the application using the toggle.
The application is now configured to accept client connections from and issue OAuth 2.0 tokens to the JavaScript example PingOne applications and tutorials covered by this documentation.
This tutorial requires you to configure your PingOne Advanced Identity Cloud tenant as follows:
Task 1. Create a demo user
The samples and tutorials in this documentation often require that you have an identity set up so that you can test authentication.
To create a demo user in PingOne Advanced Identity Cloud, follow these steps:
-
Log in to your PingOne Advanced Identity Cloud tenant.
-
In the left panel, click Identities > Manage.
-
Click New Alpha realm - User.
-
Enter the following details:
-
Username =
demo -
First Name =
Demo -
Last Name =
User -
Email Address =
demo.user@example.com -
Password =
Ch4ng3it!
-
-
Click Save.
Task 2. Register a public OAuth 2.0 client
Public clients do not use a client secret to obtain tokens because they are unable to keep them hidden. The Orchestration SDKs commonly use this type of client to obtain tokens, as they cannot guarantee safekeeping of the client credentials in a browser or on a mobile device.
To register a public OAuth 2.0 client application for use with the SDKs in PingOne Advanced Identity Cloud, follow these steps:
-
Log in to your PingOne Advanced Identity Cloud tenant.
-
In the left panel, click Applications.
-
Click Custom Application.
-
Select OIDC - OpenId Connect as the sign-in method, and then click Next.
-
Select Native / SPA as the application type, and then click Next.
-
In Name, enter a name for the application, such as
Public SDK Client. -
In Owners, select a user that is responsible for maintaining the application, and then click Next.
When trying out the SDKs, you could select the demouser you created previously. -
In Client ID, enter
sdkPublicClient -
Select Configure for SDK Sample Apps.
-
Click Create Application.
PingOne Advanced Identity Cloud creates the application and displays the details screen.
-
On the Sign On tab:
-
In Sign-In URLs, ensure the following values appear, or add them if they don’t:
https://localhost:8443/callback.htmlAlso add any other domains where you host SDK applications. -
In Grant Types, ensure the following values appear:
Authorization CodeRefresh Token -
In Scopes, ensure the following values appear:
openid profile email address
-
-
Click Show advanced settings, and on the Authentication tab, confirm the following properties:
-
In Token Endpoint Authentication Method, select
none. -
In Client Type, select
Public. -
Enable the Implied Consent property.
-
-
Click Save.
The application is now configured to accept client connections from and issue OAuth 2.0 tokens to the example applications and tutorials covered by this documentation.
Task 3. Configure the OAuth 2.0 provider
The provider specifies the supported OAuth 2.0 configuration options for a realm.
To ensure the PingOne Advanced Identity Cloud OAuth 2.0 provider service is configured for use with the Orchestration SDKs, follow these steps:
-
In your PingOne Advanced Identity Cloud tenant, navigate to Native Consoles > Access Management.
-
In the left panel, click Services.
-
In the list of services, click OAuth2 Provider.
-
On the Core tab, ensure Issue Refresh Tokens is enabled.
-
On the Consent tab, ensure Allow Clients to Skip Consent is enabled.
-
Click Save Changes.
This tutorial requires you to configure your AM server as follows:
Task 1. Create a demo user
The samples and tutorials in this documentation often require that you have an identity set up so that you can test authentication.
To create a demo user in PingAM, follow these steps:
-
Log in to the PingAM admin UI as an administrator.
-
Navigate to Identities, and then click Add Identity.
-
Enter the following details:
-
User ID =
demo -
Password =
Ch4ng3it! -
Email Address =
demo.user@example.com
-
-
Click Create.
Task 2. Register a public OAuth 2.0 client
Public clients do not use a client secret to obtain tokens because they are unable to keep them hidden. The Orchestration SDKs commonly use this type of client to obtain tokens, as they cannot guarantee safekeeping of the client credentials in a browser or on a mobile device.
To register a public OAuth 2.0 client application for use with the SDKs in AM, follow these steps:
-
Log in to the PingAM admin UI as an administrator.
-
Navigate to Applications > OAuth 2.0 > Clients, and then click Add Client.
-
In Client ID, enter
sdkPublicClient. -
Leave Client secret empty.
-
In Redirection URIs, enter the following values:
https://localhost:8443/callback.htmlThe Orchestration SDK for JavaScript attempts to load the redirect page to capture the OAuth 2.0
codeandstatequery parameters that the server appended to the redirect URL.If the page you redirect to does not exist, takes a long time to load, or runs any JavaScript you might get a timeout, delayed authentication, or unexpected errors.
To ensure the best user experience, we highly recommend that you redirect to a static HTML page with minimal HTML and no JavaScript when obtaining OAuth 2.0 tokens.
Also add any other domains where you will be hosting SDK applications. -
In Scopes, enter the following values:
openid profile email address -
Click Create.
PingAM creates the new OAuth 2.0 client, and displays the properties for further configuration.
-
On the Core tab:
-
In Client type, select
Public. -
Disable Allow wildcard ports in redirect URIs.
-
Click Save Changes.
-
-
On the Advanced tab:
-
In Grant Types, enter the following values:
Authorization Code Refresh Token -
In Token Endpoint Authentication Method, select
None. -
Enable the Implied consent property.
-
-
Click Save Changes.
Task 3. Configure the OAuth 2.0 provider
The provider specifies the supported OAuth 2.0 configuration options for a realm.
To ensure the PingAM OAuth 2.0 provider service is configured for use with the Orchestration SDKs, follow these steps:
-
Log in to the PingAM admin UI as an administrator.
-
In the left panel, click Services.
-
In the list of services, click OAuth2 Provider.
-
On the Core tab, ensure Issue Refresh Tokens is enabled.
-
On the Consent tab, ensure Allow Clients to Skip Consent is enabled.
-
Click Save Changes.
This tutorial requires you to configure your PingFederate server as follows:
Task 1. Register a public OAuth 2.0 client
OAuth 2.0 client application profiles define how applications connect to PingFederate and obtain OAuth 2.0 tokens.
To allow the Orchestration SDKs to connect to PingFederate and obtain OAuth 2.0 tokens, you must register an OAuth 2.0 client application:
-
Log in to the PingFederate administration console as an administrator.
-
Navigate to .
-
Click Add Client.
PingFederate displays the Clients | Client page.
-
In Client ID and Name, enter a name for the profile, for example
sdkPublicClientMake a note of the Client ID value, you will need it when you configure the sample code.
-
In Client Authentication, select
None. -
In Redirect URIs, add the following:
https://localhost:8443Also add any other URLs where you host SDK applications.
Failure to add redirect URLs that exactly match your client app’s values can cause PingFederate to display an error message such as
Redirect URI mismatchwhen attempting to end a session by redirecting from the SDK. -
In Allowed Grant Types, select the following values:
Authorization CodeRefresh Token -
In the OpenID Connect section:
-
In Logout Mode, select Ping Front-Channel
-
In Front-Channel Logout URIs, add the following:
https://localhost:8443Also add any other URLs that redirect users to PingFederate to end their session.
Failure to add sign off URLs that exactly match your client app’s values can cause PingFederate to display an error message such as
invalid post logout redirect URIwhen attempting to end a session by redirecting from the SDK. -
In Post-Logout Redirect URIs, add the following:
https://localhost:8443
-
-
Click Save.
After changing PingFederate configuration using the administration console, you must replicate the changes to each server node in the cluster before they take effect.
In the PingFederate administration console, navigate to System > Server > Cluster Management, and click Replicate.
The application is now configured to accept client connections from and issue OAuth 2.0 tokens to the Orchestration SDK PingFederate example applications and tutorials covered by this documentation.
Task 2. Configure CORS
Cross-origin resource sharing (CORS) lets user agents make cross-domain server requests. In PingFederate, you can configure CORS to allow browsers or apps from trusted domains to access protected resources.
To configure CORS in PingFederate follow these steps:
-
Log in to the PingFederate administration console as an administrator.
-
Navigate to .
-
In the Cross-Origin Resource Sharing Settings section, in the Allowed Origin field, enter any DNS aliases you use for your SDK apps.
This documentation assumes the following configuration:
Property Values Allowed Originhttps://localhost:8443 -
Click Save.
After changing PingFederate configuration using the administration console, you must replicate the changes to each server node in the cluster before they take effect.
In the PingFederate administration console, navigate to System > Server > Cluster Management, and click Replicate.
Your PingFederate server is now able to accept connections from origins hosting apps built with the Orchestration SDKs.
Step 1. Installing modules
The OIDC client for JavaScript as available as an npm module at @forgerock/oidc-client.
To install the module into your JavaScript project, run the following npm command:
npm install @forgerock/oidc-client@2.0.0
After installation, import the module into your app as follows:
import { oidc } from '@forgerock/oidc-client';
Step 2. Configuring connection properties
Configure the oidc module to connect to your OpenID Connect 1.0-compliant authorization server:
oidc moduleconst oidcClient = oidc({
clientId: '6c7eb89a-66e9-ab12-cd34-eeaf795650b2',
redirectUri: 'https://localhost:8443/callback.html',
scope: 'openid profile email phone',
serverConfig: {
wellknown:
'https://auth.pingone.ca/3072206d-c6ce-ch15-m0nd-f87e972c7cc3/as/.well-known/openid-configuration',
},
});
Update the following properties with values that match your environment:
- clientId
-
The client ID of your OAuth 2.0 application.
For example,
6c7eb89a-66e9-ab12-cd34-eeaf795650b2 - redirectUri
-
The redirect URI as configured in the OAuth 2.0 client profile.
This value must exactly match one of the values configured in your OAuth 2.0 client.
For example,
https://localhost:8443/callback.html - scope
-
The scopes you added to your OAuth 2.0 application.
For example,
openid profile email phone - serverConfig.wellknown
-
The
.well-knownendpoint from your OAuth 2.0 application.How do I find my PingOne .well-known URL?
To find the
.well-knownendpoint for an OAuth 2.0 client in PingOne:-
Log in to your PingOne administration console.
-
Go to Applications > Applications, and then select your OAuth 2.0 client.
For example, sdkPublicClient.
-
On the Overview tab, expand the Connection Details section, and then copy the OIDC Discovery Endpoint value.
How do I form my PingFederate .well-known URL?
To form the
.well-knownendpoint for a PingFederate server:-
Log in to your PingFederate administration console.
-
Navigate to .
-
Make a note of the Base URL value.
For example,
https://pingfed.example.comDo not use the admin console URL. -
Append
/.well-known/openid-configurationafter the base URL value to form the.well-knownendpoint of your server.For example,
https://pingfed.example.com/.well-known/openid-configuration.The SDK reads the OAuth 2.0 paths it requires from this endpoint.
How do I find my PingOne Advanced Identity Cloud
.well-knownURL?You can view the
.well-knownendpoint for an OAuth 2.0 client in the PingOne Advanced Identity Cloud admin console:-
Log in to your PingOne Advanced Identity Cloud administration console.
-
Click Applications, and then select the OAuth 2.0 client you created earlier. For example, sdkPublicClient.
-
On the Sign On tab, in the Client Credentials section, copy the Discovery URI value.
For example,
https://openam-forgerock-sdks.forgeblocks.com/am/oauth2/alpha/.well-known/openid-configuration
If you are using a custom domain, your
.well-knownis formed as follows:https://<custom-domain-fqdn>/.well-known/openid-configurationLearn more in Access OIDC configuration discovery endpoint.
How do I find my PingAM
.well-knownURL?To form the
.well-knownURL for an PingAM server, concatenate the following information into a single URL:-
The base URL of the PingAM component of your deployment, including the port number and deployment path.
For example,
https://openam.example.com:8443/openam -
The string
/oauth2 -
The hierarchy of the realm that contains the OAuth 2.0 client.
You must specify the entire hierarchy of the realm, starting at the Top Level Realm. Prefix each realm in the hierarchy with the
realms/keyword.For example,
/realms/root/realms/customersIf you omit the realm hierarchy, the top level
ROOTrealm is used by default. -
The string
/.well-known/openid-configuration
For example,
https://auth.pingone.ca/3072206d-c6ce-ch15-m0nd-f87e972c7cc3/as/.well-known/openid-configuration -
Step 3. Starting the OAuth 2.0 flow
The oidc module provides two choices for starting an OAuth 2.0 flow.
- Redirect
-
The module obtains the URL for authenticating users from your authorization server (AS) and adds the necessary parameters.
You then redirect the user to the URL to authenticate, after which the AS redirects them back to your application.
- Background
-
If the user already has a session, the module can attempt to start an OAuth 2.0 flow in the background. The module makes a request to your authorization server (AS) in an iframe using the session tokens.
On success, the AS returns the
codeandstateparameters, ready to exchange for an access token, without having to redirect to the AS.On failure, for example if the session isn’t valid, the request returns the URL to redirect to for authentication, just like in the redirect method above.
-
Redirect
-
Background
Use the oidcClient.authorize.url() function to determine the URL to use to authenticate the user.
Redirect the user to the URL you receive to authenticate.
On success, the AS redirects the user back to your app, and includes the code and state parameters that you can exchange for an access token.
authorize.url() functionconst authorizeUrl = await oidcClient.authorize.url();
if (typeof authorizeUrl !== 'string' && 'error' in authorizeUrl) {
console.error('Authorization URL Error:', authorizeUrl);
displayError(authorizeUrl);
return;
} else {
console.log('Authorization URL:', authorizeUrl);
window.location.assign(authorizeUrl);
}
Use the oidcClient.authorize.background() function to attempt to get OAuth 2.0 tokens for a user without having to redirect to the AS.
The AS responds with either the code and state parameters that you can exchange for an access token, or a redirectUrl to use for authenticating the user.
background() functionconst response = await oidcClient.authorize.background();
if ('error' in response) {
console.error('Authorization Error:', response);
if (response.redirectUrl) {
window.location.assign(response.redirectUrl);
} else {
console.log('Authorization failed with no ability to redirect:', response);
}
return;
// Handle success response from background authorization
} else if ('code' in response) {
console.log('Authorization Code:', response.code);
}
Step 4. Obtaining an Access Token
After starting the OAuth 2.0 flow and authenticating the user, the server redirects control back to your application. Your application receives the OAuth 2.0 code and state parameters it needs to continue the flow and obtain an access token.
Use the token.exchange() function to obtain an access token on behalf of the user, passing in the code and state parameters:
token.exchange() and handle the resultconst code = urlParams.get('code');
const state = urlParams.get('state');
if (code && state) {
const response = await oidcClient.token.exchange(code, state);
displayTokenResponse(response);
}
Step 5. Obtaining user info
The oidc module implements a user object that represents a user’s authentication session.
Call the info() function on this object to retrieve details about the user from the server:
const userInfo = await oidcClient.user.info();
if ('error' in userInfo) {
console.error('User Info Error:', userInfo);
} else {
console.log('User Info:', userInfo);
}
Step 6. Revoking tokens and signing out
You can call the following functions to revoke OAuth 2.0 tokens, and sign out the user from the server:
oidcClient.token.revoke()-
Revokes the OAuth 2.0 tokens on the server, and deletes them from storage.
oidcClient.user.logout()-
Removes any session tokens the user may have, and contacts the server to end the user’s session.