Protecting your Single Page Application
Integrating the IDaaS Auth SDK in your SPA
Once you've set up your OIDC configuration in IDaaS, you can simplify integrating secure authentication into your SPAs with the IDaaS Auth SDKs.
JavaScript SDK | React SDK |
---|
Installation
- JavaScript
- React
Getting Started
- JavaScript
- React
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-spa";
// 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>",
globalAudience: "<GLOBAL_AUDIENCE>",
globalScope: "<GLOBAL_SCOPE>",
globalUseRefreshToken: true | false,
});
Wrap your application in the IdaasProvider
component. You will need to pass it your
OIDC Application's clientId
and issuerUrl
.
// Wrap your application.
root.render(
<IdaasProvider clientId="<IDAAS_CLIENT_ID>" issuerUrl="<IDAAS_ISSUER_URL>">
<App />
</IdaasProvider>
);
// or can override defaults using the props below.
root.render(
<IdaasProvider
clientId="<IDAAS_CLIENT_ID>"
issuerUrl="<IDAAS_ISSUER_URL>"
globalAudience="<GLOBAL_AUDIENCE>"
globalScope="<GLOBAL_SCOPE>"
globalUseRefreshToken={true | false}
>
<App />
</IdaasProvider>
);
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
- React
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.login();
// Or you can also configure the login with the following properties.
idaasClient.login({
audience: "YOUR_AUDIENCE",
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,
popup: 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.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. 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.login({
popup: true,
acrValues: ["possession", "inherence"],
});
const idToken = idaasClient.getIdTokenClaims();
console.log(idToken);
});
Now within child components of the IdaasProvider
you can use the
useIdaas
hook to pull out the login method.
import { useIdaas } from "@entrustcorp/idaas-auth-react";
function LoginButton() {
const { login } = useIdaas();
return <button onClick={() => login()}>Login</button>;
// You can also configure the login with the following properties.
return (
<button
onClick={() =>
login({
audience: "YOUR_AUDIENCE",
scope: "YOUR_SCOPES",
redirectUri: "YOUR_REDIRECT_URI", // You will also need to configure the login redirectUri in your Generic SPA Application
useRefreshToken: true | false,
popup: true | false,
})
}
>
Login
</button>
);
}
You can specify the type(s) of authentication that are acceptable to be used to authenticate the user. Successful authentication via methods that do not fall under the specified authentication types(s) will be treated as a failed authentication attempt.
If you need to know the ACR value used to retrieve an access token the received access token must not be opaque. An opaque token is returned if an audience is not specified.
const { getIdTokenClaims } = useIdaas();
const handleOnClick = () => {
await login({ popup: true, acrValues: ["possession", "inherence"] });
const idToken = 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
- React
<button id="logout">Logout</button>
document.getElementById("logout").addEventListener("click", () => {
idaasClient.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.logout({ redirectUri: "<MY_LOGOUT_REDIRECT_URI>" });
});
function LogoutPage() {
const { logout } = useIdaas();
return <button onClick={() => logout()}>Logout</button>;
// End the user session when the logout button is clicked.
return (
// You will also need to configure redirectUri in your Generic SPA Application.
<button onClick={() => logout({ redirectUri: "YOUR_REDIRECT_URI" })}>
Logout
</button>
);
}
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
- React
<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");
}
});
import { useIdaas } from "@entrustcorp/idaas-auth-react";
...
const { isAuthenticated } = useIdaas();
const handleOnClick = async () => {
if (isAuthenticated) {
console.log("User is authenticated");
} else {
console.log("User is not authenticated");
}
};
...
<button onClick={handleOnClick}>Click to Check Authentication Status</button>;
Protecting components
With the React SDK, you have access to the RequireAuth
component. Children wrapped in RequireAuth
will only render if the user is logged in. You can provide an onUnauthenticated
method to determin what to do with with an unauthenticated user who tries to access the protected children. The suggested use is to use your router to redirect to the login page.
import { RequireAuth } from "@entrustcorp/idaas-auth-react";
...
function Profile() {
return (
<RequireAuth onUnauthenticated={()=>redirect('/login')}>
...
</RequireAuth>)
};
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
- React
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);
});
You can get information about the logged in user sending a request to the userInfo
endpoint
import { useIdaas } from "@entrustcorp/idaas-auth-react";
...
const { getUserInfo } = useIdaas();
const userInfo = await getUserInfo();
...
<div>Welcome {userInfo?.given_name}</div>
Fetching the Stored ID Token
You can configure IDaaS to include desired claims in the ID Token
import { useIdaas } from "@entrustcorp/idaas-auth-react";
...
const { user } = useIdaas();
...
<div>Welcome {user.given_name}</div>