Jump to content
  • JavaScript API: New Capabilities in Spotfire® 12.0


    The Spotfire® JavaScript API allows embedding a Spotfire analysis into other web applications and the ability to have bi-directional interaction between Spotfire and other applications. This article outlines the improvements made to the JavaScript API in Spotfire 12.0.

    Introduction

    The JavaScript API allows embedding a Spotfire analysis into other web applications, also known as web mashups. This API comes with the ability to have bi-directional interaction between the two applications. This API is not as rich as the C# API, and it focuses on marking, filtering, page navigation and reading and modifying document properties.

     

    Technically all Spotfire instances are loaded into separate iframes, and the API will internally communicate between Spotfire and the other application. The technical communication channel has been changed over the years, but we have been able to keep the API backward compatible without any need for the web mashups to adapt to a new API.

     

    Due to recent, and in some cases future, changes to the major browsers, the API needed to be extended when it comes to authentication. This will require all web mashups to be re-written, but the changes needed only affects how the Spotfire analysis is loaded. In addition there are configurations needed to be performed by the customer. This does not come without benefit; Spotfire web mashups will now be fully integrated with the configured authentication mechanism.

    Spotfire® JavaScript API Overview

    Spotfire JavaScript API Reference

    JavaScript API 12.0 improvements

    Support for all major browsers

    In the near future all major browsers will remove support for third party cookies, which will make it impossible to embed old versions of Spotfire in an iframe. This is regardless of how this is done; via the old generated embed link, manually crafted links to Spotfire analyses or properly used Spotfire JavaScript API implementations.

     

    In 12.0 the entire Web Player has been modified to support token based authentication (no cookies needed). Minor adjustments to the web mashups must be made to benefit from this new functionality; The authentication flow has been rewritten in order to achieve this. The rest of the API, such as working with marking, filtering, page changes etc, is unchanged.

    Support for OAuth authentication flow

    The web mashup will now always act as an API client towards the Spotfire Server. Each request from the mashup will include an access token, which the Web Mashup client establishes through an OAuth2 Authorization Code flow.

     

    To use the new API the client first must be registered on the Spotfire Server (for on-premises deployments, or other cloud deployments than Spotfire Cloud). For Spotfire Cloud, the client would need to be registered in the Spotfire Cloud, but this ability isn?t available yet.

     

    Registration on the Spotfire Server is done using the existing register-api-client command of the Spotfire Server command-line configuration tool. Example:

    register-api-client --name="JavaScript API client" -Sapi.js-api -Soffline --client-profile=user_agent -Gauthorization_code -Grefresh_token -Ahttps://example.com -Rhttps://example.com/foo/return

     

    The parts in blue in the example above depend on the environment. The -A argument specifies an allowed JavaScript origin (where the Web Mashup will be running). The -R argument specifies the redirect URI to which the browser will be returned after the user has authenticated (the ?OAuth redirect page?) - it must be the same value as given to the new redirectUri setting. 

     

    Running the command above will give an output like this:

    Successfully registered a new API client with the display name 'JavaScript API client':

    Client ID: 12f4a3c33d377ed5c7ab476d69ea52d1.oauth-clients.spotfire.tibco.com

    No client secret issued (public client)

    To view the full client configuration, please use the 'show-oauth2-client' command.

    To get a list of all existing clients, please use the 'list-oauth2-clients' command.

    To delete a registered client, please use the 'delete-oauth2-client' command.

     

    After registration the client ID given in the output must be set in the clientId setting of the web mashup.

     

    Some notes:

    • All API clients are normally required to use https. This applies to JavaScript API clients as well. It is however possible to lift this requirement using the security.oauth2.client.redirect-uri-must-use-https configuration property.
    • If an API client has been registered as shown in the example below then each user will need to give consent for the API client to Access Spotfire visualizations and dashboards on your behalf, and embed these into web pages. The administrator registering the API client may specify that end-user consent isn?t needed for a particular API client by specifying --require-end-user-consent=false.
    • The API allows for ?silent authentication? (where an access token is automatically issued to the client). For this to work the user must be already authenticated (which requires the use of cookies, and may not work in all browsers), or it must be possible to authenticate the user without user interaction (an example of this would be Kerberos authentication). Set the silent setting of the Web Mashup to true to attempt silent authentication.
    • The API client must provide an access token even when the analysis is available to anonymous users. The API is now explicit about the use of anonymous authentication. Set the anonymous setting of the Web Mashup to true to request such a token.

    New API

    The new API is about how to authenticate the user and retrieve an instance of a spotfire.webPlayer.Application. From there on there JavaScript API is unaltered. The retrieved Application instance is then used just like before to open one or more instances of spotfire.webPlayer.Document.

    spotfire.webPlayer.setApiVersion(version)

    This needs to be specified once in a web mashup, and the version should be specified in the same way as previously; in the script src tag, or in the createApplication methods described in this document.

     

    spotfire.webPlayer.authenticate(authSettings)

    Asynchronous method to establish an authentication token. The authSettings object has the following properties:

    • server - The Spotfire server url.
    • clientId - The id retrieved when the client was registered
    • redirectUri - The redirect page registered in the API client
    • anonymous - Optional bool value. See client registration for more information
    • silent - Optional bool value. See client registration for more information

    spotfire.webPlayer.connect(connectSettings)

    Asynchronous method to connect to the Spotfire server and create an instance of a spotfire.webPlayer.Application. The connectSettings object has the following properties:

    • token - The return value from spotfire.webPlayer.authenticate
    • path - The library path (or library id) to the Spotfire analysis
    • customization - UI customization settings as an anonymous JS object.
    • openParameters - Configuration block, a set of parameter assignments (to document properties, information links etc) and configuration statements (set filter, apply bookmark etc) that can be used to configure the analysis before it becomes interactive to the user. Note that the configuration block should not be URL encoded in this context.
    • reconnect - Boolean value indicating if the Web Mashup should reconnect to the Spotfire analysis on page reload 

    spotfire.webPlayer.oauthEnd()

    This method is called from the authentication redirect page. When called the authentication token will be fetched, and the browser will be redirected back to the original web mashup page.

    Sample Web Mashup

    An advanced web mashup will naturally include more logic, but this includes all the changes made to 12.0. 

    Using Promises

    The new asynchronous style (JavaScript Promise based) will allow the users to write code in new ways.

    <!DOCTYPE html>
    <html>
        <head>
            <title>Mashup Test</title>
            <script type="text/javascript" src="https://[spotfire Server]/spotfire/js-api/oauth.js"></script>
            <link rel="stylesheet" href="mashupstyle.css" />
        </head>
    
        <body>
            <div id="wrapper"></div>
            <script>
                // Basic settings
                let server = "[spotfire Server URL]";
                let customization = { showToolBar: false };
                let path = "[Library path to analysis file, e.g. /Sample]";
                let openParameters = "";
                let reconnect = false;
                let apiVersion = "12.0"; // New oauth specific settings
                let clientId = "[Client ID as retrieved from the API client registration]";
                let redirectUri = "[e.g. http://myserver.com:8080/oauthEnd.html]";
                let anonymous = false;
                let silent = false; // Specify API version
                spotfire.webPlayer.setApiVersion(apiVersion); // Using promises to chain the entire process
                spotfire.webPlayer
                    .authenticate({ server, clientId, redirectUri, anonymous, silent })
                    .then(connect)
                    .then(open)
                    .catch(onError);
                function connect(token) {
                    return spotfire.webPlayer.connect({ token, path, reconnect, customization, openParameters });
                }
                function open(app) {
                    let doc = app.openDocument("wrapper");
                }
                function onError(err) {
                    console.error("Spotfire JavaScript API Error:", err.category, err.code, err.message);
                }
            </script>
        </body>
    </html>
     

    Using await

    An alternative to using promises is to use the await keyword.

    Note that using await keyword in top level JavaScript requires the script to be created as a module (<script type="module">).

    <!DOCTYPE html>
    <html>
            <head>
            <title>Web Mashup supporting all browsers</title>
            <script type="text/javascript" src="https://[spotfire Server]/spotfire/js-api/oauth.js"></script>
            <link rel="stylesheet" href="mashupstyle.css" />
        </head>
        <body>
            <div id="wrapper"></div>
            <script type="module">
                // Basic settings
                let server = "[spotfire Server URL]";
                let customization = { showToolBar: false };
                let path = "[Library path to analysis file, e.g. /Sample]";
                let openParameters = "";
                let reconnect = false;
                let apiVersion = "12.0"; // New oauth specific settings
                let clientId = "[Client ID as retrieved from the API client registration]";
                let redirectUri = "[e.g. http://myserver.com:8080/oauthEnd.html]";
                let anonymous = false;
                let silent = false; // Specify API version
                spotfire.webPlayer.setApiVersion(apiVersion); // Authenticate to the Spotfire server
                let authSettings = { server, clientId, redirectUri, anonymous, silent };
                let token = await spotfire.webPlayer.authenticate(authSettings); // Connect to Spotfire
                let connectSettings = { token, path, customization, openParameters, reconnect };
                let app = await spotfire.webPlayer.connect(connectSettings); // Open the document
                let doc = app.openDocument("wrapper");
            </script>           
        </body>
    </html>

    OAuth redirect page

    The redirect page declared in the API client registration must be hosted on the same domain as the web mashup itself. If a customer has multiple web mashups it is sufficient to server all these with a single API client and a single redirect page. The redirect page only needs to call spotfire.webPlayer.oauthEnd().

    <!DOCTYPE html>
    <html>
        <head>
            <title>Generic OAuth Endpoint</title>
            <script src="https://[spotfire Server]/spotfire/js-api/oauth.js"></script>
            <script>
                spotfire.webPlayer.oauthEnd();
            </script>
        </head>
    </html>

     

    Error handling

    Historically error handling has been poor for developers of a web mashup, or while loading an analysis. The new methods added in 12.0 (spotfire.webPlayer.authenticate and spotfire.webPlayer.connect) can result in errors for different reasons. All errors are categorized and contains in addition to a semi user friendly error message also a code and a category to guide the developer of the mashup. 

    Category API_USAGE

    This category signals that the developer most likely has used the API in an incorrect way. The possible codes - messages are:

    • INVALID_SERVER: "Invalid server URL '{0}'.",
    • INVALID_REDIRECT_URL: "Invalid domain. The redirect URL ('{0}') must match the domain of the current page ('{1}').",
    • NON_SILENT_ANONYMOUS_FLOW: "Anonymous authentication must use silent mode.",
    • INVALID_TOKEN: "Invalid authorization token.",
    • MISSING_TOKEN: "Missing authorization token.",
    • INVALID_PATH: "Invalid analysis path '{0}'.",
    • INVALID_API_VERSION: "Invalid API version '{0}'.",
    • SET_API_VERSION: "API version must be set once."

    Category OAUTH

    This category is used for errors that can occur during the authorization flow. These can be either configuration errors or merely an expected error if the end user for example does not consent to allow access to Spotfire.

    • ACCESS_DENIED: "The user or authorization server denied access to Spotfire.",
    • INVALID_REQUEST: "The request is missing a parameter, contains an invalid parameter, includes a parameter more than once, or is otherwise invalid.",
    • INVALID_SCOPE: "The requested scope is invalid or unknown.",
    • SERVER_ERROR: "Server error.",
    • TEMPORARILY_UNAVAILABLE: "The authorization server is temporarily unavailable.",
    • UNAUTHORIZED_CLIENT: "The client is not allowed to request an authorization code.",
    • UNSUPPORTED_RESPONSE_TYPE: "The server does not support obtaining an authorization code."

    Category SERVER_CONFIGURATION

    These errors indicate that the configuration of the server is incorrect.

    • ENDPOINT: "Failed to get OAuth endpoint.",
    • HASH_ALGORITHM: "Hashing algorithm {0} is not configured on server {1}.",
    • SCOPE: "Scope {0} is not configured on server {1}.",
    • RESPONSE_TYPE: "OAuth response type {0} is not configured on server {1}."

    Category INTERNAL_ERROR

    These errors might be temporary, due to network errors, or the user trying to manipulate the code.

    • FAILED_TO_REFRESH_TOKEN: "Failed to refresh OAuth token. Reason: '{0}'.",
    • INVALID_STATE: "Invalid OAuth state.",
    • FAILED_TO_LOAD_API: "Failed to load the Spotfire JavaScript API version. Reason unknown.",

    User Feedback

    Recommended Comments

    There are no comments to display.


×
×
  • Create New...