Digipass S3 is now DigipassONE. This section is currently being updated to reflect our new name.

Using the App SDK

Prev Next

To use the App SDK, initialize an SDK instance and call the appropriate method to perform registration, authentication, transaction confirmation, or credential management. All common functions, such as network communications and processing of Server data, are handled by the App SDK. All SDK APIs are asynchronous methods and return a JS Promise object.

For more details on the interfaces, see the Client API Docs.

SessionData

Most App SDK methods use a SessionData object that represents a user's signed-in state. A session token is created when the user signs into your app, after either conventional or FIDO authentication.

Nok Nok uses a JSON Web Token (JWT) as its session token. To understand how JWTs are created and used during conventional sign-in as well as FIDO authentication, see JWT Session token section Understanding the Session Token.

Conventional Authentication

For conventional authentication, e.g. password authentication, it is recommended to use the external authentication method (see section Using External Authentication). Another approach is for your backend server to create a session token after it verifies the user and return the token to your app. Your app must insert that session token in a SessionData object. Once you've done that, pass that object to any App SDK methods that require a SessionData object.

The code below shows how your app can create a SessionData object that contains a JWT, highlighted in the example. Hard coding a JWT is not recommended. You can decode the JWT at jwt.io to see its contents or easily modify its values. To generate a JWT, see Building Tutorial Web App.

var token =
"eyJraWQiOiJoczI1Nl9rZXkiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzbWl0aCIsImF1ZCI6ImRlZmF1bHQiLCJuYmYiOjE1NTczNTc2ODEsImlzcyI6Imh0dHBzOi8vYWNtZS5jb206ODQ0MyIsImV4cCI6MTU1NzM2MTI4MSwiaWF0IjoxNTU3MzU3NjgxfQ.23kj5oj6flVNQl9QDa82XmJdkgHoAdctMY_HmYfZddY";
var sessionData = {
    sessionKey: token
};

If your Web App backend already returns the SessionData object as shown in the code block above, you can skip this step and use SessionData as is.

FIDO Authentication

After a user registers a FIDO authentication method, they can sign in with Nok Nok's Adaptive Authentication or FIDO authentication. Upon successful authentication, The App SDK returns a SessionData object containing a session token. Use that object when you call other App SDK methods that require a SessionData object.

In addition to the session token, you can assign the username to SessionData's userName attribute. This enables you to pass in a username to App SDK methods that authenticate.

Refer to the SessionData class in the Client API Docs for more information.

Storing a Persistent Device ID

The Nok Nok Authentication Server uses a Device ID to identify the user's device when applying adaptive rules. The App SDK generates and stores a Device ID in the browser's local storage. But the browser deletes the local storage if it is not accessed in 7 days. The method of storing a persistent Device ID depends on whether your app and the Nok Nok API Server are hosted on the same origin.

  • If your app and the Nok Nok API Server are hosted on the same origin, the App SDK can store a persistent Device ID in an HttpOnly secure cookie. In order to use this feature, your app calls NNLStorage.initialize() during initialization:

NNLStorage.initialize("https://<nnl_apiserver_domain>:<port>/nnlgateway/storage");
  • If your app and the API Server are hosted on different origins, your app stores the Device ID in an HttpOnly secure cookie. Then, during initialization, your app retrieves the Device ID from the cookie and calls AppSdkInfo.setDeviceId(deviceId) to pass the Device ID to the App SDK.

For a sample implementation, see the getCustomDeviceIdFromCookie() function in the file utils.js, its usage in the initialize() function in the file Controller.js, and the file DeviceIDServlet.java in gwtutorial.

Setting an Active User

For user data caching and push handles to work correctly in the App SDK, you must tell the App SDK that there is an active user as soon as the username is known. This may be even before the user successfully authenticates. Do this by calling the setActiveUser() method in class UserDataCache.

UserDataCache.getInstance().setActiveUser(userName);

This designates the user as an active user.

After successful authentication, call setActiveUser() again. This is necessary because authentication may have been performed without a userName. Call setActiveUser() after successful authentication no matter which authentication method the user signs in with.

To ensure a good user experience: When the user logs out, you must tell the App SDK that there is no longer an active user. The code below sets the active user to null.

UserDataCache.getInstance().setActiveUser(null);

For more information about user data caching, refer to UserDataCache class in the Client API Docs.

Managing Session Renewal and Expiration Time

To monitor user activity use the AppSDK class NNLSessionManager. In addition, it:

  • renews the session automatically when the user is actively using the application

  • warns the user when the session is about to expire because of inactivity

  • logs the user out when there is no activity and the session expires

To take advantage of NNLSessionManager:

Step 1. Use script tags to load utils.js and then session-manager.js.

<head>
  . . .
  <script src="https://<nnl_apiserver_domain>:<port>/nnlappsdk‑<version>/js/utils.js">
  </script>
  <script src="https://<nnl_apiserver_domain>:<port>/nnlappsdk‑<version>/js/session-manager.js">
  </script>
  . . .
</head>

Step 2. Define a class that implements the ISessionNotification interface, including the following 3 methods.

  1. onRenewSession()
    NNLSessionManager calls this method when the session needs to be renewed. This method renews the session and returns a Promise. The Promise resolves with a SessionData object containing sessionKey and exp fields with the new session key and expiration timestamp in seconds from epoch respectively. The Promise is rejected if the renewal fails.

  2. onSessionUpdated()
    NNLSessionManager calls this method when the session is renewed in another browser tab. This method synchronizes the session data that was updated by the onRenewSession() method in the other browser tab.

  3. onSessionExpired()
    This method logs the user out. NNLSessionManager calls this method in two cases:

    1. Session expiration time is reached because of user inactivity. In this case NNLSessionManager calls onSessionExpired() in all browser tabs that have called NLSessionManager.startSession().

    2. Your web application calls NNLSessionManager.stopSession() after the user has explicitly logged out. In this case NNLSessionManager calls onSessionExpired() from any background browser tabs that have previously called NNLSessionManager.startSession().

Step 3. Initialize NNLSessionManager with an object of your ISessionNotification class.

NNLSessionManager.initialize(sessionNotification, configuration);

Where sessionNotification is an instance of the ISessionNotification class you defined in 2. above. The configuration parameter is optional. If configuration is null, the default configuration options are used as described in the Client API Docs.

Step 4. When the user logs into the application, start the monitoring by calling startSession().

NNLSessionManager.startSession(expirationTime);

expirationTime is the application's session expiration time stamp in seconds from epoch. After successful authentication, the API Server returns the expiration time inside the SessionData object's field exp.

Step 5. When the user logs out, call stopSession() to stop the monitoring.

NNLSessionManager.stopSession();

Refer to the NNLSessionManager class in the Client API Docs for details about these methods and their arguments.

Working Example in Tutorial Web App

Refer to the SessionManager class in the file js/session.js for an example of ISessionNotification implementation.

Session Refresh

If your application has its own session manager then you may choose not to use the NNLSessionManager. If you don't use the NNLSessionManager, then your application still needs to provide the new session token to the App SDK whenever your app renews the session token. Below is an example of an application passing renewed session data to the App SDK.

OperationResultListener.getInstance().onSessionDataUpdated(newSessionData)

See Client API docs for more info.

Extras

The App SDK has a general purpose mechanism for passing optional data to its methods. It uses a parameter of type Extras which is a dictionary of key-value pairs, so you can pass in an arbitrary amount of data. The key identifies the type of data. Valid keys are defined as properties of the Global Extras object in the Client API Docs. This parameter is called extras, authOpts, suggestRegOpts, or signUpOpts.

You can find examples of the most common use of extras while performing specific tasks.

Error Handling

The App SDK is based on JS Promises. Whenever an error happens, the promise is rejected and the calling code can get the result in a catch block. For example:

try {
    const result = await adaptiveUI.getAuthenticationView().getController().enable(AutoStart.AUTO_FIDO);
    // Success
} catch(result) {
    // Error
    // result                is an instance of AdaptiveResult (see Client API Docs)
    // result.outcome        specifies the error code from Outcome object
    // result.method         the authentication method that causes the failure 
    //                       (if any)
    // result.exception      a client side exception, e.g. DOMException (if any)
    // result.additionalErrorInfo     additional error information (if any)
    // result.operationType        the last REST API operation (e.g. INIT_ADAPTIVE)
    // result.serverStatusCode     the statusCode from last REST API operation
    // result.correlationId  the correlation ID of the operation
    // result.facetId        the WebApp facetID (i.e. origin)
}

When the promise is rejected, the AdaptiveResult object always contains an outcome field that specifies the error. The error code descriptions are defined on the Global Outcome object, see the Client API Docs for more information.

App IQ

To improve troubleshooting the App SDK includes a built-in error reporting service, App IQ, that is implemented as an NNLErrorReporterListener class. This listener captures operation failures and automatically reports them to the public REST API endpoint of your choosing.

This feature allows an application to:

  • Centralize and standardize error logging.

  • Enrich error data with diagnostic metadata such as device type, OS, and App SDK version.

  • Choose which error codes should or should not be reported. By Default, the App SDK reports all error codes except:

    • CANCELED

    • SYSTEM_CANCELED

    • SERVER_USER_NOT_FOUND

For a description of each error code, see Web Result Codes.

To take advantage of the default behavior, instantiate an NNLErrorReporterListener that includes your server endpoint URL, the tenant-specific API key, and an Object ID provider.

const errorReporterListener = new NNLErrorReporterListener(
    'https://errors.example.com/report',
    'your-api-key',
    function() { // Object ID Provider callback
        return new Promise(function(resolve) {
            // Retrieve/generate the Object ID.
            const objectID = 'the-object-id';
            resolve(objectID);
        });
    }
);
OperationResultListener.addInstance(errorReporterListener);

The objectID is retrieved for each error, ensuring that a fresh and accurate device identifier is reported.

To control which error types are excluded from reporting, provide a custom list of Outcome values in disallowedErrorTypes:

const disallowedErrorTypes = [Outcome.CANCELED,Outcome.SYSTEM_CANCELED, Outcome.SERVER_USER_NOT_FOUND, Outcome.FAILURE];
const errorReporterListener = new NNLErrorReporterListener(
    'https://errors.example.com/report',
    'your-api-key',
    function() { // Object ID Provider callback
        return new Promise(function(resolve) {
            // Retrieve/generate the Object ID.
            const objectID = 'the-object-id';
            resolve(objectID);
        });
    },
    disallowedErrorTypes
);
OperationResultListener.addInstance(errorReporterListener);

The App SDK only reports errors with status code that are not included in disallowedErrorTypes.

Working Example in Tutorial App

  • Refer to enableErrorReporter in the file js/Controller.js.

Health Check Service

The App SDK provides an API that checks if the API Server and the Authentication Server are running. This health check service returns real-time status information to your application.

Example Usage:

var serverHealthUrl = "https://<nnl_apiserver_domain>:<port>/nnlgateway/health";
try {
    const result = await HealthCheck.performHealthCheck(serverHealthUrl);
    console.log("HealthCheck result: " + JSON.stringify(result));
} catch(result) {
    console.log("HealthCheck result: " + JSON.stringify(result));
}

The App SDK returns the health check result as a JSON object. This object contains status codes for both the API Server and, if available, for the Authentication Server.

Example Success Result:

{
    "apiServer": {
        "statusCode": 4000
    },
    "authServer":{
        "statusCode": 4000
    }
}

In case of an error, the response will also contain the HTTP status code of the operation.

Example Failure Result:

{
    "apiServer": {
        "statusCode": 5601
    },
    "httpStatusCode": 500
}

For a comprehensive list of possible status codes, see Status Codes.

Working Example in Tutorial App

  • Refer to the enableHealthCheck flag and checkServerHealth() function in the file js/Controller.js.

Supported Authenticators

The App SDK supports all common authentication methods including:

  • FIDO2: passkey, Touch ID, Face ID, fingerprint sensor, Windows Hello, security keys.

  • FIDO using a second device, also known as Out-of-band authentication.

  • External Authentication including passwords.

  • SMS OTP, Email OTP, and Photo ID.

  • On the Cordova platform, the App SDK supports FIDO UAF authenticators.

Obtaining 3DS Data

EMV 3DS is a protocol developed by EMVCo that enables the exchange of data to authenticate the user and prevent fraud, especially during transactions. The App SDK supports this protocol by including the EMV 3DS FIDO blob in the SessionData object that it returns after a successful registration and/or authentication operation.

The App SDK includes the EMV 3DS information inside the SessionData object only when the API Server's EMV 3DS plugin is active. By default this plugin is active. If you have deactivated this plugin, see EMV 3DS Generator Plugin for instructions to reactivate it.

Once you receive the result.sessionData object, the example below shows how to extract the EMV 3DS data from it.

// After the user has just registered or authenticated, sessionData is available.
var sessionData = result.sessionData;
// You can extract 3DS data from the sessionData
var emv3ds = sessionData.emv3dsData;Retrieving SessionData

To retrieve SessionData after a FIDO registration operation, see Retrieving SessionData. The sessionData object is inside the Result object.

To retrieve SessionData after a successful FIDO authentication, see Sign-in or Transaction. The sessionData object is inside the AdaptiveResult object. The App SDK includes the EMV 3DS information in SessionData only if the successful authentication rule has Include EMV 3DS Data checked. Otherwise, the value of sessionData.emv3dsData is null.

For details about the contents of the EMV 3DS FIDO blob, see the Nok Nok™ Data Types Used by the App SDK Tech Note.

Implementing Dark Mode

The views displayed by the App SDK do not use dark mode by default. If your application supports dark mode and uses the built-in App SDK views, you can configure how they handle dark mode.

If your application switches in and out of dark mode when the browser does, then add the following code before any built-in App SDK view is displayed:

AppSdkConfig.darkMode = NNLDarkMode.AUTOMATIC;

If your application is always in dark mode and does not switch out of dark mode when the browser does, then add the following code before any built-in App SDK view is displayed:

AppSdkConfig.darkMode = NNLDarkMode.ON;