Protecting a Single Page Application (SPA)
Integrating the IDaaS Auth SDK in your SPA
Once you've set up your OIDC configuration in IDaaS, you can easily add authentication to your Single Page Application with the IDaaS Authentication SDK:
Installation
- JavaScript
With npm:
npm install @entrustcorp/idaas-auth-js
Getting Started
Before deploying to production, make sure you update your Content Security Policy to allow API calls to your IDaaS tenant.
- JavaScript
Create an IdaasClient before rendering or initializing your application. You should
only ever have one instance of the client.
import { IdaasClient } from "@entrustcorp/idaas-auth-js";
// Create a client.
const defaultIdaasClient = new IdaasClient({
clientId: "<IDAAS_CLIENT_ID>",
issuerUrl: "<IDAAS_ISSUER_URL>",
});
// or create a customized variant by setting the global values to be used.
const customIdaasClient = new IdaasClient(
{
clientId: "<IDAAS_CLIENT_ID>",
issuerUrl: "<IDAAS_ISSUER_URL>"
},
{
audience: "<AUDIENCE>", // If access token is for a resource server
scope: "<SCOPE>",
useRefreshToken: true | false,
acrValues: ["<ACR_VALUES>"],
maxAge: <MAX_AGE>
});
Logging In
The IDaaS Auth SDK supports two methods of authenticating your users:
-
login with redirect - The browser will redirect the user to your IDaaS login page to authenticate. After authenticating, the user will be redirected back to your application.
-
login with popup - The browser will open a popup window with the IDaaS login page for the user to authenticate. After authenticating, the popup window will be closed.
tipWhen using popup, if the user closes the popup or clicks "Back", an error is thrown. You may use a try/catch to handle this.
- JavaScript
Using the IdaasClient instance you created you can access the login method.
<button id="login-with-redirect">Click to Login With Redirect</button>
// redirect to the IDaaS login page when the login button is clicked
document.getElementById("login-with-redirect").addEventListener("click", () => {
idaasClient.oidc.login({ redirectUri: <IDAAS_SERVER>, popup: false });
// Or you can also configure the login with the following properties.
idaasClient.oidc.login(
{
redirectUri: "YOUR_IDAAS_SERVER"
popup: false },
{
audience: "YOUR_AUDIENCE", // If access token is for a resource server
scope: "YOUR_SCOPES",
redirectUri: "YOUR_REDIRECT_URI", // You will also need to configure the login redirectUri in your OIDC Application in IDaaS
useRefreshToken: true | false
}
);
});
You will need to invoke the handleRedirect method on the page that you redirect to after logging in.
// in your callback route (<MY_LOGIN_REDIRECT_URI>)
window.addEventListener("load", async () => {
await idaasClient.oidc.handleRedirect();
// if the user has successfully authenticated, you can access the user's claims from their ID token:
const idToken = idaasClient.getIdTokenClaims();
console.log(idToken);
});
You can specify the methods of authentication that are acceptable to be used to authenticate the user and authentication recentness. Successful authentication via methods that do not fall under the specified authentication methods will be treated as a failed authentication attempt.
To use this value later, the received access token must not be opaque.
document
.getElementById("login-with-popup")
.addEventListener("click", async () => {
// authenticate using an authentication method that falls under the `possession` or `inherence` authentication types.
await idaasClient.oidc.login(
{
redirectUri: "YOUR_IDAAS_SERVER"
popup: true
},
{
audience: "YOUR_AUDIENCE", // If access token is for a resource server
scope: "YOUR_SCOPES",
redirectUri: "YOUR_REDIRECT_URI", // You will also need to configure the login redirectUri in your OIDC Application in IDaaS
useRefreshToken: true | false,
acrValues: ["possession", "inherence"],
maxAge: 30
}
);
const idToken = idaasClient.getIdTokenClaims();
console.log(idToken);
});
Logging Out
End the user session by using the logout method. This will log the user out of IDaaS as well.
- JavaScript
<button id="logout">Logout</button>
document.getElementById("logout").addEventListener("click", () => {
idaasClient.oidc.logout();
});
// You can also configure the logout.
document.getElementById("logout").addEventListener("click", () => {
// You will also need to configure redirectUri in your Generic SPA Application.
idaasClient.oidc.logout({ redirectUri: "<MY_LOGOUT_REDIRECT_URI>" });
});
Authentication Status
Authentication status is determined by the presence of a non-expired ID token. If an ID token is stored and not expired, the user is authenticated.
- JavaScript
<button id="check-authentication">Click to Check Authentication Status</button>
document
.getElementById("check-authentication")
.addEventListener("click", () => {
const isAuthenticated = idaasClient.isAuthenticated();
if (isAuthenticated) {
console.log("User is authenticated");
} else {
console.log("User is not authenticated");
}
});
Getting Information About the User
When a user is logged in, you have access to the the claims that were returned in their Access and ID tokens.
- JavaScript
You can get information about the logged in user sending a request to the userInfo endpoint.
<button id="get-information">Click to get Information</button>
document
.getElementById("get-information")
.addEventListener("click", async () => {
// assumes the user is logged in and an access token is stored
const userInfo = await idaasClient.getUserInfo();
console.log("User Info", userInfo);
});
Fetching the Stored ID Token
<button id="get-id-token">Click to get ID token</button>
document.getElementById("get-id-token").addEventListener("click", () => {
// assumes the user is authenticated
const idToken = idaasClient.getIdTokenClaims();
console.log("ID Token", idToken);
});
#### Fetching the Stored Access Token
```html
<button id="get-access-token">Click to get access token</button>
document.getElementById("get-id-token").addEventListener("click", () => {
// assumes the user is authenticated
const accessToken = idaasClient.getAccessToken();
console.log("Access Token", accessToken);
});
Content Security Policy (CSP)
The IDaaS Auth SDK will send API requests to your IDaaS tenant. You will need to ensure the Content Security Policy of your web application is updated to include your IDaaS tenant hostname as an allowed connection source. For more information regarding CSP, see the MDN Content Security Policy documentation.
The following must be set in your Content Security Policy for the SDK to work. Replace entrust.us.trustedauth.com with
your IDaaS tenant hostname.
connect-src 'entrust.us.trustedauth.com'