ForgeRock JavaScript SDK
The ForgeRock JavaScript SDK is a toolkit that allows web developers to easily integrate intelligent authentication using ForgeRock OpenAM and/or ForgeRock Identity Cloud.
Installation
npm install @forgerock/javascript-sdk
Usage
Configuration
There are a few settings to configure before invoking SDK components. When authenticating users with trees, you'll need to provide the server configuration and tree name. If also obtaining OAuth tokens, you'll provide the client ID, redirect URI, and desired scope.
forgerock.Config.set({
clientId: 'my_client_id',
redirectUri: 'https://myapp.domain.com/callback',
scope: 'openid profile me.read',
serverConfig: { baseUrl: 'https://mytenant.forgeblocks.local/am/' },
tree: 'UsernamePassword',
});
The following UI examples assume this configuration has already been set and are intentionally very minimal to demonstrate key SDK usage.
Basic Example
Using the FRUser
component is the easiest way to authenticate users. This example combines it with the ExpressLogin
UI to leverage the username/password authentication tree provided out-of-the-box with ForgeRock Express tenants. All required elements are rendered by the SDK, and you can customize the experience by defining CSS styles to override our defaults.
async function signIn() {
const ui = new forgerock.ExpressLogin({ targetId: 'sdk-target' });
const user = await forgerock.FRUser.loginWithUI(ui);
window.sessionStorage.setItem('user', JSON.stringify(user));
window.location = 'authenticated.html';
}
async function signOut() {
await forgerock.FRUser.logout();
window.location = 'login.html';
}
Custom UI Example
In most real-world scenarios, you will want to have full control over the UI. In these cases, you can use FRAuth
to obtain typed callback instances from authentication trees and render the UI in whatever way makes sense for you.
In this example, a simple React app iteratively calls FRAuth.next()
until either an error occurs or a session token is obtained. A custom React component named UsernamePassword
is defined to handle the "UsernamePassword" stage in a ForgeRock Express flow.
import { FRAuth, Config } from '@forgerock/javascript-sdk';
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
error: undefined,
ssoToken: undefined,
step: undefined,
};
}
componentDidMount() {
this.nextStep();
}
nextStep = async (step) => {
step = await FRAuth.next(step).catch(this.onError);
const ssoToken = step.getSessionToken();
if (ssoToken) {
this.setState({ ssoToken });
} else {
this.setState({ step });
}
};
onError = (error) => {
this.setState({ error });
};
render() {
if (!this.state.step) {
return <p>Loading...</p>;
} else if (this.state.ssoToken) {
return <p>Authenticated!</p>;
} else if (this.state.error) {
return <p>Error: {this.state.error}</p>;
}
const stage = this.state.step.getStage();
return (
<>
<h1>Sign In</h1>
{stage === 'UsernamePassword' && (
<UsernamePassword step={this.state.step} onSubmit={this.nextStep} />
)}
{/* Create similar components for other stages */}
</>
);
}
}
function UsernamePassword(props) {
const setUsername = (e) => {
const cb = props.step.getCallbackOfType('NameCallback');
cb.setName(e.target.value);
};
const setPassword = (e) => {
const cb = props.step.getCallbackOfType('PasswordCallback');
cb.setPassword(e.target.value);
};
const onSubmit = () => {
props.onSubmit(props.step);
};
return (
<>
<input type="text" placeholder="Username" onChange={setUsername} />
<input type="password" placeholder="Password" onChange={setPassword} />
<button onClick={onSubmit}>Submit</button>
</>
);
}
export default App;
Samples
Prerequisites:
- OpenSSL is installed
- samples/js/config.js is updated to specify your SDK configuration
echo '127.0.0.1 forgerock-sdk-samples.com' | sudo tee -a /etc/hosts
npm i
npm run make_certs
npm start
npm run samples
Access the samples at https://forgerock-sdk-samples.com:3000
Trusting the Certificate
Trusting the certificate is required to avoid browser warnings and for WebAuthn to work correctly.
Chrome
Add the certificate to your keychain:
sudo npm run trust_certs
You must restart Chrome for the change to take effect.
Firefox
Import the certificate to Firefox:
- Go to Preferences > Privacy & Security > Certificates > View Certificates...
- On the Authorities tab, click Import...
- Select
certs/ca.crt
and enable option to "Trust this CA to identify websites" - Restart Firefox
E2E Tests
Preliminary E2E tests are implemented with Puppeteer. They utilize an HTML page that allows configuration of the SDK via querystring parameters at the beginning of each test scenario.
npm run e2e_server
npm run e2e_tests
To Do
- Unit tests with coverage reporting
- Expand E2E tests
- Optimizations
- Customize typedocs comments
- Link to official developer docs
License
MIT