New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@forgerock/javascript-sdk

Package Overview
Dependencies
Maintainers
10
Versions
86
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@forgerock/javascript-sdk

ForgeRock JavaScript SDK

  • 2.0.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
1.8K
decreased by-71.99%
Maintainers
10
Weekly downloads
 
Created
Source

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

Sample Usage

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 your application.

In the following example, a simple React app iteratively calls FRAuth.next() until either an error occurs or a session token is obtained. The custom React component <UsernamePassword /> is defined to handle an authentication step named "UsernamePassword".

import { FRAuth, Config } from '@forgerock/javascript-sdk';
import React from 'react';

class App extends React.Component {
  constructor(props) {
    super(props);

    // Initialize application state
    this.state = {
      error: undefined,
      ssoToken: undefined,
      step: undefined,
    };
  }

  componentDidMount() {
    // Set configuration defaults
    Config.set({
      clientId: '<Your OAuth Client ID>',
      redirectUri: '<Your Callback URL>',
      scope: '<Your Scopes>',
      serverConfig: { baseUrl: '<Your AM URL>' },
      tree: '<Your Auth Tree in AM>',
    });

    // Start the authentication flow
    this.nextStep();
  }

  nextStep = async (step) => {
    // Get the next step in this authentication tree
    step = await FRAuth.next(step).catch(this.onError);

    // Update application state based on the response
    let ssoToken, error;
    if (step.type === 'LoginSuccess') {
      ssoToken = step.getSessionToken();
    } else if (step.type === 'LoginFailure') {
      error = step.getCode();
    }
    this.setState({ step, ssoToken, error });
  };

  onError = (error) => {
    this.setState({ error });
  };

  render() {
    // Handle init/success/failure states
    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>;
    }

    // Otherwise, select the correct component for this step
    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 */}
      </>
    );
  }
}

// Custom UI for rendering the "UsernamePassword" step
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;

Included Sample App

Prerequisites:

  • OpenSSL is installed
  • The SDK configuration is updated within samples/custom-ui/index.html to specify your AM settings
# Add host
echo '127.0.0.1 sdkapp.example.com' | sudo tee -a /etc/hosts

# Install dependencies
npm i

# Build the SDK and watch for changes
npm run watch

# Start the sample webserver
npm run start:samples

# Follow the next section to trust certificate

Access the samples at https://sdkapp.example.com:8443

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:

# MacOS
sudo npm run certs:trust

You must restart Chrome for the change to take effect.

Firefox

Import the certificate to Firefox:

  1. Go to Preferences > Privacy & Security > Certificates > View Certificates...
  2. On the Authorities tab, click Import...
  3. Select test/certs/ca.crt and enable option to "Trust this CA to identify websites"
  4. Restart Firefox

Tests

This project is configured for multiple forms of tests: unit, integration, and e2e. Compilation and linting occurs as a pre-commit hook, and all tests are run as a pre-push hook.

E2E Test Requirements

Node v13.10 or higher is required to run the mock E2E server application.

To run the end-to-end tests, you'll need to add a few more domains to your host file:

# For end-to-end testing this code base, these domains also need to be added
echo '127.0.0.1 auth.example.com api.example.com' | sudo tee -a /etc/hosts

Environment Configuration

VariablePurpose
AM_URLFull URL to your OpenAM instance
BASE_URLBase URL for your application
CLIENT_IDYour OAuth client ID
REALM_PATHThe realm in which trees, users, OAuth clients reside
SCOPEThe scopes to request when getting access tokens
TREEThe authentication tree name to use for authentication
USERNAMEThe username to use when authenticating
PASSWORDThe password to use when authenticating

Running E2E tests require a running server (or "backend") for the necessary request/response relationship. Configuration of the server is done within env.config.ts file within the tests/e2e/ directory. The default shown below runs the tests against a mock server:

export const AM_URL = 'https://auth.example.com:9443/am';
export const BASE_URL = 'https://sdkapp.example.com:8443';
export const CLIENT_ID = 'WebOAuthClient';
export const PASSWORD = 'ieH034K&-zlwqh3V_';
export const REALM_PATH = 'root';
export const RESOURCE_URL = 'https://api.example.com:9443/account';
export const SCOPE = 'openid profile me.read';
export const TREE = 'BasicLogin';
export const USERNAME = '57a5b4e4-6999-4b45-bf86-a4f2e5d4b629';

If you prefer to test against a live environment, you will need to configure the .env file to use your OpenAM instance and its public OAuth client.

Troubleshooting

DOMException: Blocked a frame with origin "{url}" from accessing a cross-origin frame (in browser console)

This occurs when OpenAM returns the authorization code, but the redirect_uri doesn't match what's configured for the OAuth client. Tests use a path of /callback, so your OAuth client should be configured with a redirect_uri of {BASE_URL}/callback (e.g. https://sdkapp.example.com:8443/_callback).

Version History

Our version history can be viewed by visiting our CHANGELOG.md.

License

MIT

FAQs

Package last updated on 30 Jun 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc