You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 16 Next »

xID Connect is a Javascript helper library that offers simple integration of the xID service for OIDC Clients. There are several ways to integrate xID, each with different user experiences and considerations. For example, opening xID in a new window or redirecting the user to a separate webpage. In more detail:

  • xID Connect expects a configuration with the appropriate session parameters to be passed when initialising the library or triggering a login action.
  • The chosen integration method may cause a window, redirect, iframe or inline dialog to appear showing any dialogs relevant for the xID session.
  • Depending on the chosen protocol flow, HTTP endpoints at the back-end of the OIDC Client must be implemented to perform appropriate Token requests to receive user data.

This documentation is divided in the following sections:

Front-end implementation

1. Load xID Connect

Add the following HTML snippet to your OIDC Client front-end :

Example loading xID Connect library
<script async defer src="https://bankidapis.no/js/bid-xid_connect.bundle.min.js"></script>

This will make available an object XID attached to the global window object: window.XID

2. Initialise xID Connect with parameters

In your OIDC Client front-end, listen for the xid-loaded event, and call the initialisation API. Parameters are discussed below.

Example of xid-loaded handler
function onXIDLoaded() {
    // Initialise xID with required parameters
	window.XID.doInit({..});
}
 
document.body.addEventListener( 'xid-loaded', onXIDLoaded, false );

Parameters

The most important parameters are as follows, some of which are identical to parameters to the Authorize endpoint of the REST API. 

ParameterDescriptionDefault
client_idA string specifying the ID given when registering the OIDC Client in question with the OIDC Provider fromBankID. 
scope

A string of resource types (dataset) belonging to the user to request access to.

Each scope / resource type must be separated by space.

'openid'
methodThe chosen xID Connect integration method, explained here.'window'
response_type

The chosen authentication response type, explained here.

Ex. 'code' or 'token'

'code'

Depending on response_type the following parameters may be important:

ParameterDescriptionDefault
token_endpointAbsolute URL to HTTP endpoint on OIDC Client back-end to retrieve access/ID token in exchange for authorization code (if using code response_type).
'/oauth/token'
userinfo_endpointAbsolute URL to HTTP endpoint on OIDC Client back-end to retrieve user information using access token.
'/oauth/userinfo'

Other relevant, but optional, parameters include the following, some of which are identical to parameters to the Authorize endpoint of the REST API. 

ParameterDescriptionDefault
redirect_uriAbsolute URL to the HTTP endpoint on OIDC Client back-end receiving the authentication response from xID.
(xIDs internal callback handler)
response_mode

Set the format used when returning parameters from the Authorization Endpoint via redirect_uri

'query'
noStepupSet to true to disallow step-up from xID to the BankID IDP.
false
user_profileSet user info such as NNIN or phone number / birthdate if required for step-up to the BankID IDP.
''

The full list of parameter list is found in the JS API Reference.

Integration methods

There are several ways to integrate xID in your application, each with different user experiences and considerations. However, the xID functionality and appearance remain the same regardless of the integration method.

MethodDescription
window
A popular (and default) implementation choice is window. When xID Connect is triggered it will open the OIDC session in a new window (pop-up). Note that an user action should trigger this session as otherwise pop-up blockers might block the window.
inline

A DOM element ID can be provided to XID.doConnect() to host an iframe which opens the OIDC session inline in your application.

There is also a special integration which will display a modal dialogue overlaying your application. This method is useful when triggering xID Connect upon loading the application to avoid pop-up blockers. This method is described here XXXX.

redirect

(not fully tested)

xID Connect can redirect the user away from your application to a separate web page for the entire xID login session before returning to a given callback URL. When using this method its important to set redirect_uri to point to a HTTP endpoint on the OIDC Client back-end which can receive authorisation code / tokens.

Protocol flows for authentication

xID supports the different protocol flows defined for the Open ID Connect standard, as explained here

Currently, only the authorization code flow is fully functional with xID Connect. Support for implicit/hybrid is coming.

Authorisation code flow

response_type: 'code'

 This is the most secure and recommended method as the client_secret is not leaked into the client application. It is also the default method used with xID Connect.

A time limited one-time code, authorisation code, is granted to redirect_uri which in turn can be used to fetch a long living access token. The access token can then be used to fetch user information.

  1. code returned as parameter in response to redirect_uri:  https://example.com/callback?code=oMsCeLvIaQm6bTrgtp7
  2. Exchange code for access token and ID token by sending a HTTP POST request to the xID IDP token endpoint as explained here
  3. Retrieve consented user information by sending a HTTP GET request to the xID IDP userinfo endpoint as explained here

xID Connect automatically handles the client code for the token exchange and provides API for getting user information for the current session via window.XID.doGetUserInfo  

Never embed or send the client_secret to the client application.

Implicit flow

response_type: 'token'

This flow returns an access_token directly in the response to redirect_uri, bypassing the client_secret/code exchange from the Authorisation code flow, allowing the request userinfo directly. Meant for applications without backend.

Hybrid flow

response_type: 'hybrid'

Combination of code grant and implicit flow. Authorisation code and tokens can be delivered to redirect_uri.

For increased security in a production environment, it is highly encouraged to use nonce and state parameters when interacting with the xID service.

Example

Example parameters for a merchant application
// Initialise xID with required parameters
window.XID.doInit({
    // Merchant given client ID on the xID service
	client_id: 'myApplication',
	// The resource scopes merchant want to gain access to for the user
	scope: 'openid address',
    // Implementation method, open the session in a new window
	method: 'window',
    // Merchant backend endpoints for performing token/userinfo calls.
	token_endpoint: 'https://example.com/oauth2/token',
	userinfo_endpoint: 'https://example.com/oauth2/userinfo',
});

3. Start xID login

To start the xID login process call the window.XID.doConnect() function giving a callback function.

The callback function is provided with the returning accessToken and any error messages if something has gone wrong. For example, by user cancellation.

Example

Example calling doConnect and logging accessToken
// Start xID login providing a callback
window.XID.doConnect( function (err, accessToken) {
	if ( err ) {
    	// handle xID connect error
    }
    else {
        // client is now connected, store ‘accessToken’ if needed
        doGetXidUserInfo();
    }
});

4. Get user info

A common callback action is to fetch user information as the access token stored in the current xID Connect session.

xID Connect provides the API function window.XID.doGetUserInfo() for this task.

Example

Example calling doGetUserInfo() in a callback for doConnect()
function doGetUserInfo() {
	window.XID.doGetUserInfo( function (err, user) {
		if ( err ){
			// handle error
		}
		else {
			// handle user
		}
	});
}

 

Back-end implementation

When using the authorisation code flow with xID Connect the library expects the merchant to implement a server middleware to handle OAUTH requests to receive tokens and user info from xID IDP.

This middleware is needed in order to safely store the required parameter client_secret away from the client.

xID Connect will by default automatically call these HTTP endpoints in this mode.

If you use the implicit flow, there is no need for any server side implementation.

Token endpoint

When a code is received, xID Connect will call the token endpoint to receive an access_token

xID Connect will store this token in the current client session. For increased security, you may avoid sending this token back to xID Connect request.

URLAs specified in configuration parameter token_endpoint
Request modePOST with parameters as application/x-www-form-urlencoded data
Request parameters


grant_typeGrant type is always authorization_code
codeValue from response of the foregoing Authorize  request
redirect_uriRedirect URI used in the foregoing Authorize request
client_idNot supported since the OIDC clients must always authenticate
xID IDP Response /oauth/token

JSON

{
    access_token: "654fe6f11ad61ceb1697d643b5fc59", 
    token_type: "Bearer", 
    expires_in: 3600, 
    scope: "openid phone address", 
    id_token: "...."  // JWT
}


For documentation on the corresponding response to xID IDP see Token

Userinfo endpoint

Using the access token (which also could be stored on the server) to access user information xID IDP.

URLAs specified in configuration parameter userinfo_endpoint
Request modePOST with parameters as application/x-www-form-urlencoded data
Request parameters


access_tokenAccess token to be used as authorization to access xID IDP endpoint
token_typeHow access token shall be passed to xID OIDC endpoint (
xID IDO response /oauth/userinfo

JSON

{
"sub": "9578-6000-4-127698",
"iss": "https://preprod.bankidapis.no",
"iat": 1485866449,
"exp": 1485870048,
"preferred_username": "Testesen, Test",
"name": "Testesen, Test",
"given_name": "Test",
"family_name": "Testesen",
"birthdate": "1980-03-09",
"nnin": "09038000010"
}

For documentation on the corresponding response to xID IDP see Userinfo

Full examples

Window example

HTML
<button>Logg inn med xID</button>

<a class="logout" href="">Logg ut</a>
<a class="reset" href="">Slett xID</a>
Javascript
<script type="text/javascript">
    function onXIDLoaded() {
        // Initialise xID with required parameters
        window.XID.doInit({
            // Merchant given client ID on the xID service
            client_id: 'your_client_id',
            // The resource scopes merchant want to gain access to for the user
            scope: 'openid address',
            // Implementation method, open the session in a new window
            method: 'window',
            // Merchant backend endpoints for performing token/userinfo calls.
            token_endpoint: 'http://localhost/oauth/token',
            userinfo_endpoint: 'http://localhost/oauth/userinfo'
        });
    }

    function onXIDButtonClick() {
        window.XID.doConnect({
            callback: function( err, data ) {
				if ( err ) {
					return;
				}
 
				// Call directly GetUserInfo in callback
                window.XID.doGetUserInfo( function (err, user) {
                    console.log(err);
                    console.log(user);
                });
            }
        });
    }

    function onXIDLogoutClick() {
        window.XID.doLogout();
    }

    function onXIDResetClick() {
        window.XID.doReset();
    }
    var button = document.querySelector('button');
    var logout = document.querySelector('a.logout');
    var reset = document.querySelector('a.reset');

    button.addEventListener('click', onXIDButtonClick, false);
    logout.addEventListener('click', onXIDLogoutClick, false);
    reset.addEventListener('click', onXIDResetClick, false);
    document.body.addEventListener( 'xid-loaded', onXIDLoaded, false);
</script>

<script async defer src="https://localhost:7443/js/bid-xid_connect.bundle.min.js"></script>


Inline login modal example

 

CSS
<link rel="stylesheet" href="https://preview.bankidapis.no/xid/css/bid-xid_connect.min.css">
HTML
<button>Logg inn med xID</button>
 
<a class="logout" href="">Logg ut</a>
<a class="reset" href="">Slett xID</a>

 
<!-- Required markup for the out-of-the-box inline modal dialog -->
<div class="bid__dialog" data-dialog="xid-login-modal" role="dialog">
    <div class="bid__dialog__container">
        <main class="bid__dialog__main">
            <section class="bid__dialog__section bid--scrollable">
                <div class="bid__dialog__section__container">
                    <article id="authenticate-client"></article>
                </div>
            </section>
        </main>
    </div>
</div>
Javascript
<script type="text/javascript">
    function onXIDLoaded() {
        // Initialise xID with required parameters
        window.XID.doInit({
            // Merchant given client ID on the xID service
            client_id: 'your_client_id',
            // The resource scopes merchant want to gain access to for the user
            scope: 'openid address',
            // Implementation method, open the session in a iframe
            method: 'inline',
            // Merchant backend endpoints for performing token/userinfo calls.
            token_endpoint: 'http://localhost:3005/oauth/token',
            userinfo_endpoint: 'http://localhost:3005/oauth/userinfo'
        });
    }

    function onXIDButtonClick() {
        window.XID.doConnect({
            callback: function( err, accessToken ) {
				if ( err ) {
					return;
				}
 
				// Call directly GetUserInfo in callback
                window.XID.doGetUserInfo( function (err, user) {
                    console.log(err);
                    console.log(user);
                });
            },
			// Activate the inline modal mode,
            inlineModalWindow: true,
			// DOM element ID to place the injected login iframe
            inlineElementID: 'authenticate-client'
        });
    }

    function onXIDLogoutClick() {
        window.XID.doLogout();
    }
 
    function onXIDResetClick() {
        window.XID.doReset();
    }

    var button = document.querySelector('button');
    var logout = document.querySelector('a.logout');
    var reset = document.querySelector('a.reset');

    button.addEventListener('click', onXIDButtonClick, false);
    logout.addEventListener('click', onXIDLogoutClick, false);
    reset.addEventListener('click', onXIDResetClick, false);
    document.body.addEventListener( 'xid-loaded', onXIDLoaded, false);
</script>
<script async defer src="https://preview.bankidapis.no/xid/js/bid-xid_connect.bundle.min.js"></script>

Implicit mode example

 

This example will currently fail on doGetUserInfo due to CORS restrictions in the pilot phase.
HTML
<button>Logg inn med xID</button>
 
<a class="logout" href="">Logg ut</a>
<a class="reset" href="">Slett xID</a>
Javascript
<script type="text/javascript">
    function onXIDLoaded() {
        // Initialise xID with required parameters
        window.XID.doInit({
            // Merchant given client ID on the xID service
            client_id: 'your_client_id',
            // The resource scopes merchant want to gain access to for the user
            scope: 'openid address',
            // Implementation method, open the session in a iframe
            method: 'inline',
            // xID IDP endpoints for performing userinfo call.
            userinfo_endpoint: 'https://preview.bankidapis.com/xid/oauth/userinfo'
			// Activate implicit flow mode by setting response type to token
            response_type: 'token',
			// Set response mode to query string when delivering parameters to the redirect_uri 
            response_mode: 'query'
        });
    }

    function onXIDButtonClick() {
        window.XID.doConnect({
            callback: function( err, data ) {
				if ( err ) {
					return;
				}
 
				// Call directly GetUserInfo in callback
                window.XID.doGetUserInfo( function (err, user) {
                    console.log(err);
                    console.log(user);
                }, data.access_token, data.token_type, "token");
            }
        });
    }

    function onXIDLogoutClick() {
        window.XID.doLogout();
    }
 
    function onXIDResetClick() {
        window.XID.doReset();
    }

    var button = document.querySelector('button');
    var logout = document.querySelector('a.logout');
    var reset = document.querySelector('a.reset');

    button.addEventListener('click', onXIDButtonClick, false);
    logout.addEventListener('click', onXIDLogoutClick, false);
    reset.addEventListener('click', onXIDResetClick, false);
    document.body.addEventListener( 'xid-loaded', onXIDLoaded, false);
</script>
<script async defer src="https://preview.bankidapis.no/xid/js/bid-xid_connect.bundle.min.js"></script>


JS API Reference

Configuration

Configuration is set by passing an object to XID.doInit() or the config parameter of XID.doConnect(). The following parameters are supported, some of which are identical to parameters to the Authorize endpoint of the REST API. 

ParameterDescriptionDefault
client_idA string specifying the client ID given when registering to the xID central service.
 
scope

A string of resource types (dataset) belonging to the user to request access to.

Each scope / resource type must be separated by space.

'openid'
methodThe chosen xID Connect integration method, explained here.
'window'
response_type

The chosen authentication response type, explained here.

Ex. 'code' or 'token'

'code'
response_mode

Set the format used when returning parameters from the Authorization Endpoint via redirect_uri

'query'
token_endpointAbsolute URL to HTTP endpoint on merchant server-side to retrieve access/ID token in exchange for authorization code (if using code response_type).
'/oauth/token'
userinfo_endpointAbsolute URL to HTTP endpoint on merchant server-side to retrieve user information using access token.
'/oauth/userinfo'
redirect_uriHTTP endpoint receiving the authentication response from xID 
oauth_url

Absolute URL to the xID IDP OAUTH endpoint.

Ex. https://preview.bankidapis.no/oauth

Likely never applicable to change.

(default OAUTH endpoint for the xID service)
client_typePreset the OIDC client type, one of XID, BID, BIM or (empty).
'XID'
forceClientPrompt

Set to true to force the user to always confirm the xID client usage

Corresponds with the login hint forceconfirm

false
skipClientPrompt

Set to true to always skip the xID client usage confirmation

Corresponds to the login hint directConsent

false
noStepupSet to true to disallow step-up to the BankID IDP.
false
user_profileSet user info such as NNIN or phone number / birthdate if required for step-up to the BankID IDP.
''
stateIncrease security towards cross-site request forgery by verifying this value in the requests and responses
'untouched'
nonceProvide a nonce value for securing the integrity of the id_token 
grant_typeThis field always contains the value authorization_code, as defined in the OAuth 2.0 specification.
'authorization_code'

Methods

XID.doInit( config{...} )

Sets the configuration for the current session towards xID IDP.

ParameterDescriptionDefaultRequired
configSee Configuration above x

 

XID.doConnect ( callback(err, data), [config{..}, onActionCallback, inlineOnLoadCallback, inlineModalWindow, inlineElementID] )

Starts xID login session with the given configuration set with doInit().

If an access token is already active, the callback is directly called without calling xID IDP. To avoid this, call XID.doLogout() and try again.

ParameterDescriptionDefaultRequired
callback

Function to handle response from Authorize call.

Arguments are:

  • err - error messages, if any
  • data - returned object with accessToken
 x
configConfig parameters can be provided which will override session parameters for this session only.
{}
 
onActionCallbackCalled for each action in xID iframe
null 
 
inlineOnLoadCallbackCalled onload for injected iframe
null 
 

inlineModalWindow

Set to true to activate special inline login modal window.

Only active when used with inline integration method.

false
 
inlineElementIDID of DOM element to inject xID login iframe into.
null
 

 

XID.doGetUserInfo ( callback(err, user), [accessToken, tokenType, responseType] )

ParameterDescriptionDefaultRequired
callback

Function to handle response from userinfo call.

Arguments are:

  • err - error messages, if any
  • user - user object with data
 x
accessTokenOptionally provide own accessToken.
null
 
tokenTypeOptionally provide own tokenType.
null
 
responseTypeSet to token if userInfo request should go directly to oauth endpoint instead of through the middleware.
'code'
 

XID.doLogout()

Removes the current sessions access token and resets xID Connector state. 

XID.doReset()

Removes the local xID cookies for the current user. (advanced functionality) 

Events

NameDescription
xid-loadedTriggered on document.body element when xID Connect is loaded and ready to receive API calls

 

 

  


 

 

 

  • No labels