Below are a few examples on how to use the JS Connector, each showing different combinations of user experience and message flow: 

Loading JS Connector asynchronously

You can load the JS Connector asynchronously to not block loading of the page. Just remember to disable login buttons or other triggers using doConnect etc. until loading has completed.

Remember to not call OIDC.doConnect before the entire page is loaded! 

<html>
  <head>
    <script>
		function init() {
        	OIDC.doInit( {
            	// URL to OIDC service
            	oauth_url: '<oidc-baseurl>/protocol/openid-connect/auth',
	            // Merchant given client ID on the OIDC service
            	// TODO: Replace this with your own!
            	client_id: 'your_client_id',
            	// Your callback URL that will receive the Authorization Grant response
            	// TODO: Replace this with your own!
            	redirect_uri: 'https://yourdomain.com/oidc/callback'
        	} );
    	};
		document.body.addEventListener( 'oidc-connector-loaded', init, false);
	</script>
    <script src="<connector-baseurl>/connector.bundle.min.js" async defer></script>
  </head>
  <body>
  </body>
</html>

Multiple login buttons with different parameters

If you want to have one login button with one set of parameters and another button with another, you simply add configuration to the doConnect calls as needed.

For example, if some buttons have a different scope applied:

<html>
  <head>
  </head>
  <body>
	<button id="oidc-login" disabled>Login</button>
	<button id="oidc-login-scope" disabled>Login with another scope</button>
 
  	<script>
    	// Handle button click and start login
    	function onOIDCButtonClick( scope ) {
        	OIDC.doConnect({
         		config: {
			   		scope: scope
				}
        	});
    	}
    
		function init() {
        	OIDC.doInit( {
            	// URL to OIDC service
            	oauth_url: '<oidc-baseurl>/protocol/openid-connect/auth',
	            // Merchant given client ID on the OIDC service
            	// TODO: Replace this with your own!
            	client_id: 'your_client_id',
            	// Your callback URL that will receive the Authorization Grant response
            	// TODO: Replace this with your own!
            	redirect_uri: 'https://yourdomain.com/oidc/callback'
        	} );
			document.getElementById('oidc-login').disabled = false;
			document.getElementById('oidc-login-scope').disabled = false;
    	};
		document.body.addEventListener( 'oidc-connector-loaded', init, false);
 
		document.getElementById('oidc-login').addEventListener( 'click', onOIDCButtonClick.bind( null, 'openid' ), false );
		document.getElementById('oidc-login-scope').addEventListener( 'click', onOIDCButtonClick.bind( null, 'openid profile' ), false );
	</script>
    <script src="<connector-baseurl>/connector.bundle.min.js" async defer></script>
  </body>
</html>

Example with method window using a button onClick event

Here we use a login button to start a authentication using the JS Connector. The button starts disabled until the API is ready to use. The JS Connector is loaded asynchrously at the end of the page.

<html>
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="initial-scale=1.0"/>
    <title>OIDC Connector - Window mode example</title>
  </head>
  <body>

    <button disabled>Logg inn med OIDC</button>

    <script>
    	// Handle button click and start login
    	function onOIDCButtonClick() {
        	OIDC.doConnect({
         	   callback: function( err, data ) {
         	       if ( err ) {
         	           return;
         	       }
        	        console.log( data );
        	    }
        	});
    	}
    	
		function onOIDCLoaded() {
        	// Initialise OIDC with required parameters
       		OIDC.doInit({
            	// URL to OIDC service
            	oauth_url: '<oidc-baseurl>/protocol/openid-connect/auth',
            	// Merchant given client ID on the OIDC service
            	client_id: 'your_client_id',
            	// Your callback URL that will receive the Authorization Grant response
            	redirect_uri: 'https://yourdomain.com/oidc/callback',
            	// Set window as chosen integration method
            	method: 'window',
        	});
 
			// Start OIDC login on click of a button
    		var button = document.querySelector('button');
    		button.addEventListener('click', onOIDCButtonClick, false);
 
			// Enable button
			button.disabled = false;
    	}

    	// Call initialize when OIDC Connector has loaded
    	document.body.addEventListener( 'oidc-connector-loaded', onOIDCLoaded, false);
	</script>
	<script async defer src="<connector-baseurl>/connector.bundle.min.js"></script>
  </body>
</html>

 

Implicit mode example

Here we demonstrate the special implicit mode related parameters. The chosen UX method is also inline - meaning an iframe will be used to open the login. The JS Connector is loaded asynchrously at the end of the page.

<html>
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="initial-scale=1.0"/>
    <title>OIDC Connector - Implicit mode example inline</title>
  </head>
  <body>

    <button disabled>Logg inn med OIDC</button>
	<div id="auth"></div>

	<script>
    	function onOIDCButtonClick() {
        	OIDC.doConnect( {
            	inlineElementID: 'auth',
            	callback: function( err, data ) {
                	if ( err ) {
                    	return;
                	}
                	console.log( data );
            	}
        	} );
    	}
    	function onOIDCLoaded() {
        	OIDC.doInit({
            	// URL to OIDC service
           		oauth_url: '<oidc-baseurl>/protocol/openid-connect/auth',
            	// Merchant given client ID on the OIDC service
            	client_id: 'your_client_id',
            	// Your callback URL that will receive the Authorization Grant response
            	redirect_uri: 'https://yourdomain.com/oidc/callback',
            	// Set inline as chosen integration method
            	method: 'inline',
           	 	// Activate implicit flow mode by setting response type to id_token token
            	response_type: 'id_token token',
            	// Set response mode to form_post
            	response_mode: 'form_post'
        	});
		
			var button = document.querySelector('button');
	    	button.addEventListener('click', onOIDCButtonClick, false);
 
			// Enable button
			button.disabled = false;
    	}

    	document.body.addEventListener( 'oidc-connector-loaded', onOIDCLoaded, false);
	</script>
	<script async defer src="<connector-baseurl>/connector.bundle.min.js"></script>
  </body>
</html>

Callback page example for redirect_uri

This example can be implemented on your redirect_uri location to automatically pass the OIDC authentication response to the parent context (window/iframe host) which then will be passed into your callback method given in OIDC.doConnect().

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="initial-scale=1.0"/>
    <title>OIDC Connector Test Callback</title>
</head>
<body>
<!--
This callback page is rendered at callback_uri after the OIDC authorization request returns.

This is an example implementation of a callback script for those sites that use frame method inline (iframe) or window.
The idea of this page is to communicate with the BankID JS Connect instance sitting in the parent site that launched the
iframe or window in the first place.

Depending on the response methods chosen in the initial request, this page will attempt to use XDM (Cross-domain messaging)
messages to communicate to the parent site.

When this page loads it will do the following:

1. Checking a special if this was a form_post response_mode (handled by the server).
2. Retrieving response data based on response_mode chosen: form_post, query or fragment
3. Checking data received and doing an XDM event postMessage to parent Window with data.

That's it!

BankID JS Connect will now close this window/frame.
-->
<script>
	// If FORM POST, the server side handler must inject the received data here as a JSON string
    var formPost = '{form_post}';
    formPost = /{\w+}/.test(formPost) ? null : JSON.parse( formPost );

    function urlSearchToObj( search ) {
        var pairs = search.substring( 1 ).split( '&' ),
            obj = {},
            pair;

        for ( var i = 0; i < pairs.length; i ++) {
            if ( pairs[i] === '' ) {
                continue;
            }

            pair = pairs[i].split( '=' );
            obj[decodeURIComponent( pair[0] )] = decodeURIComponent( pair[1] );
        }

        return obj;
    }
    // Get form_post data, or query params, or hash fragment params
    var urlParams = formPost || urlSearchToObj( document.location.search || document.location.hash );
    var hasError = false;

    if ( urlParams['error'] ) {
        console.error( 'Received error' );
        hasError = true;
    }

    var windowParent = window.opener || window.parent;

    if ( windowParent !== window) {
        if ( !hasError && responseData ) {
            windowParent.postMessage( JSON.stringify( { type: 'oidc-connector-response-data', data: urlParams } ), '*' );
        } else {
            windowParent.postMessage( JSON.stringify( { type: 'oidc-connector-error', error: urlParams['error'] } ), '*' );
        }
    } else {
        console.warn( 'OIDCConnectorError: Could not send code, does not have parent window' );
    }
</script>

</body>
</html>
  • No labels