Initialization

Initialization sets the context of your app to the currently logged in user and is required before a user can access documents or interact with groups. Your app must verify a user and instantiate a browser session to initialize a user into the IronWeb SDK.

User Verification and Syncing

The IronWeb SDK uses JSON Web Tokens (JWT) to initialize which verifies that the user who is interacting with the SDK is a legitimate, active user within your app. Generating a valid JSON Web Token (JWT) that is tied to the currently authenticated user in your app provides a secure user assertion from your app to IronWeb.

The JWT assertion is required every time the SDK is initialized.

Browser Session Creation

The first time a user visits your app and the initialize function is run, a new unique "master" public and private key pair is generated for the user. The private key of this key pair is required anytime the user wants to approve a browser or device for usage with the SDK. In order to simplify this process the user will provide a password that will be used to securely encrypt and store their private key within the IronCore database. This password is then required for subsequent devices that the user wants to approve to decrypt their content.

For a browser session, this password is required the first time the user is synced to IronCore as well as any subsequent times that the user wants to approve a new browser session for usage with the SDK. The users password will only be necessary if the user hasn't approved the current browser session, so it won't always have to be provided each time the initialize function is run.

IronWeb.initialize()

IronWeb.initialize(jwtCallback, passwordCallback)

Parameters

Parameter Name Value Description
jwtCallback Function() => Promise<string> A function that returns a Promise that resolves with a valid JWT(string). The jwtCallback should make a call to your server and resolve with a JWT. This function will be called every time you invoke initialize.

JWT generation should not happen on the client.
passwordCallback Function(didUserExist) => Promise<string> A function that returns a Promise that resolves with a users passcode to authorize the current browser session. This method is invoked if the user did not authorize a browser session.

This method will be called with a single boolean parameter that denotes if the user has already been synced within IronCore .

Response

Returns a Promise that resolves with information about the currently initialized user.

Check Initialization Status

IronWeb.isInitialized()

Response

Returns a boolean that denotes whether the SDK is currently authenticated with a user context.

Example

The following shows an example of how you would initialize the IronWeb SDK. This example assumes that you've already created an IronCore account and have your Project, Segment, and Service Key IDs as well as a Service Key private key in PEM file format.

The first part to implement is the server side JWT generation endpoint. The following example is an implementation in NodeJS using ExpressJS with the jsonwebtoken NPM package.

Server Side

const fs = require("fs");
//Import the jsonwebtoken library
const jwt = require("jsonwebtoken");

//Read in private key file contents
const serviceKeyPrivateKey = fs.readFileSync("<PATH to key PEM file>", "utf8");

app.get("/generateJWT", (req, res) => {
    //We'll respond from this endpoint with a JWT in plaintext form
    res.type("text/plain");

    //The JWT payload is an object which contains the Project, Segment, and Service Key IDs
    //to associate with this user.
    const jwtPayload = {
        //Your unique Project ID
        pid: PROJECT_ID,
        //Your Segment ID for this Project
        sid: "SEGMENT_ID",
        //Your Service Key ID for this Project
        kid: SERVICE_KEY_ID,
    };

    const jwtToken = jwt.sign(jwtPayload, projectPrivateKey, {
        //Algorithm MUST be 'ES256' which is ECDSA using P-256 curve and SHA-256 hash algorithm
        algorithm: "ES256",
        //Token expire time. The IronCore server only supports a max of 2 minutes.
        expiresIn: "2m",
        //The JWT "subject" is the unique ID of the user who is currently
        //authenticated into your app. In NodeJS/Express this might be available
        //on the 'req.user' object
        subject: UNIQUE_ID_OF_CURRENTLY_LOGGED_IN_USER,
    });

    //Send the JWT back to the client
    res.send(jwtToken);
});

Client Side

Now that you have a server-side endpoint which will generate you a valid JWT for authenticated users in your system, you can now setup the initialize function within your client side JavaScript.

import {initialize, ErrorCodes, document} from "@ironcorelabs/ironweb";

/**
 * Request the endpoint on your server that we setup above. Since we setup the endpoint
 * above to return the token in plaintext, we need to parse the response as such.
 */
function getJWTForUser() {
    //The fetch() API returns a Promise which we can then chain to parse out
    //the plaintext content of the response, which will be a valid JWT.
    return fetch("/generateJWT").then((response) => {
        return response.text();
    });
}

/**
 * Request the users password. This function will only be called if the user
 * has not authorized this browser to access their data.
 */
function getUsersPassword(didUserExist) {
    //The `didUserExist` argument is a boolean parameter which gives you the opportunity
    //to alter the user experience for newly created/synced users.
    return new Promise((resolve, reject) => {
        const password = window.prompt("Please provide your secure password.");
        resolve(password);
    });
}

/**
 * Initialize the IronWeb SDK with the two provided callbacks. The Promise will resolve
 * once successful at which point the document/group/user methods are available to be
 * invoked
 */
initialize(getJWTForUser, getUsersPassword)
    .then((initResult) => {
        //initResult.user.id is the initialized user
        return document.list();
    })
    .then((userDocs) => {
        //Show user a list of their documents
    })
    .catch((sdkError) => {
        if (sdkError.code === ErrorCode.USER_PASSCODE_INCORRECT) {
            alert("Wrong password provided! Please try again");
        }
    });

Once you have successfully initialized the SDK you can then use it to implement the functionality required by your app via the different IronWeb SDK methods. The initialize method will need to be called upon every page refresh in your app, however the user will only need to provide their password once per session per browser they want to use.