Introduction

CoreID allows you to easily and securely authenticate users through electronic identification (eID) without any of the hassle.

The Assently CoreID Client is a javascript plugin that handles the user authentication and integration with the CoreID service and eID providers. Let us worry about integrations, security, browser support and maintenance while you focus on creating value for your users.

The CoreID Client works in both your app and your website.

Contact us at info@assently.com to get started with the free test account.

How it works

Add our javascript to your website/app, generate a token, configure with a few lines of code and you’re good to go!

When a user wants to authenticate, your application will generate an authentication token using the provided credentials and settings. It defines which eIDs you accept and how long it will be valid.

The CoreID Javascript Client is then invoked with this token, allowing the user to authenticate through CoreID and chosen eID provider.

After successful authentication, an identity token is created and returned. Once your application has verified the authenticity of the identity token, it can be used to identify the user in your application.

What you need to implement

The CoreID Client has “batteries included” and handles the majority of the work.

To authenticate a user, your application needs to handle three steps:

  1. Generate token using provided credentials (sample code)
  2. Invoke CoreID client (sample code)
  3. Verify the returned identity token (sample code)

You’ll then have a trusted identity of your user, that you can integrate with your application logic.

CoreID securely communicates with our servers which handle the integrations with the different eID Providers. For token generation and verification there are a multitude of libraries available in almost any programming language. JWT is widely supported and well documented.

Keep reading to see how to get started.


Getting started - Quick start guide

The example-code for generating and verifying tokens in this guide is in C#, but similar libraries are available in almost any language. Check the overview at https://jwt.io/.

Prerequisites

  • Configuration-values and credentials for test environment, contact us at info@assently.com if you need these
  • A test eID user, setting up Swedish BankID is the quickest if you don’t already have one. Setup instructions
  • CoreID uses a shared secret to sign and verify tokens. Your application or website needs to be able to run the code used to generate tokens serverside, as to not disclose this secret.

The CoreID implementation guide for authentication.

0. Credentials and configuration

You should have been provided with the following credentials.

  • AccountID: Your account ID at Assently or a test account id.
  • Secret or Auth Secret: Secret used to generate auth token.
  • Identity Secret: Used to validate identity token.

You’ll also need to specify the URI you’ll host the script on.

And for testing Swedish BankID you’ll specify DisplayName as “Test av Mobilt BankID”.

1. Auth Token Creation

Generate an Auth Token that will be used with the CoreID Client for this authentication session. You can use https://jwt.io to decode and debug your Auth Token.

Full documentation of the auth token.

This C# snippet uses the System.IdentityModel.Tokens.Jwt library.

public class AuthTokenService
{
    /// <param name="displayName">Display name is required for Swedish BankID and Finnish Mobiilivarmenne and should be added to token as a "dnm" claim.</param>
    /// <param name="embedHost">The URI of the host. Required claim, should be added as "hst"</param>
    /// <param name="accountId">Customer account id at Assently</param>
    /// <param name="secret">The secret that is used to sign the JWT. Provided by Assently</param>
    /// <returns>Encoded JWT string</returns>
    public string CreateToken(string displayName, string embedHost, string accountId, string secret)
    {
        // The time at which the token was issued.
        var issuedAt = (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

        var claims = new List<Claim>()
        {
            new Claim("dnm", displayName),
			// "jti" (Jwt Id) is a mandatory token identifier. Should be a GUID4.
            new Claim("jti", Guid.NewGuid().ToString()),
            new Claim("hst", embedHost),
            new Claim("iat", issuedAt.ToString()),

            // Chosen identity provider, possible to have multiple
            new Claim("aud", "se-bankid"),

        };
        // Expiration time for the token, this is how long the token can be used to start an authentication session.
        var expires = DateTime.UtcNow.Add(TimeSpan.FromMinutes(30));

        var jwt = new JwtSecurityToken(
            issuer: accountId,
            claims: claims,
            expires: expires,
            signingCredentials:
                new SigningCredentials(
                    new InMemorySymmetricSecurityKey(Encoding.UTF8.GetBytes(secret)),
                    "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
                    "http://www.w3.org/2001/04/xmlenc#sha256"
                    )
            );

        var jwtHandler = new JwtSecurityTokenHandler();
        return jwtHandler.WriteToken(jwt);
    }
}

2. Embed the client

<!-- TEST -->
<script src="https://coreid-test.assently.com/embed/coreid.js"></script>

<!-- PRODUCTION -->
<script src="https://coreid.assently.com/embed/coreid.js"></script>

3. Configure and start client

Here is a quick example of how to configure the client. The token from step 1 should be unique, so generate a new one for each session or when the view is rendered.

Full documentation of the CoreID Client

coreid_client.init({
  config: {
    allowedEids: ['*'],   // enable all eID providers
    mode: 'auth',         // sets the mode to authentication
    language: 'sv',       // set the client to use swedish language
    provider: 'se-bankid',// default provider to show on start
  },
  token: '<TOKEN FROM STEP 1>',
  callback: function(data) {
    // for example, send it back to your iOS webview:
    webkit.messageHandlers.callbackHandler.postMessage(data);
    // See full CoreID Client documentation for handling different authentication outcomes.

    console.log('CoreID response', data);
  }
});

// start the client!
coreid_client.start();

4. Identity Token Validation

The client should post the Identity Token to your server. Always verify the identity token to ensure it hasn’t been tampered with. You should also verify that the auth token and the identity token match. You can use https://jwt.io to decode and debug your Identity Token.

Full documentation of the identity token.

This C# snippet use System.IdentityModel.Tokens.Jwt library.

public class IdentityTokenService
{
    public JwtSecurityToken ValidateToken(string token)
    {

        var configuration = ConfigurationManager.AppSettings;
        var tokenHandler = new JwtSecurityTokenHandler();
        var secret = configuration["IdentitySecret"];
        var keyBytes = Encoding.UTF8.GetBytes(secret);

        var tokenValidationParameters = new TokenValidationParameters()
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new InMemorySymmetricSecurityKey(keyBytes),

            ValidateIssuer = true,
            ValidIssuer = configuration["Issuer"],
            ValidAudience = configuration["AccountId"],
            ValidateAudience = true,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.Zero,
            LifetimeValidator = (before, expires, jwttoken, validationParameters) =>
            {
                var now = DateTime.UtcNow.Add(validationParameters.ClockSkew);
                if (before.HasValue && now < before.Value)
                {
                    return false;
                }
                if (expires.HasValue && expires <= now)
                {
                    return false;
                }

                return true;
            }
        };
        SecurityToken validatedToken;

        tokenHandler.ValidateToken(token, tokenValidationParameters, out validatedToken);

        return validatedToken as JwtSecurityToken;
    }


	// Validate that authtoken and idtoken match
    public bool ValidateJwtId(HttpCookie cookie, JwtSecurityToken identityToken)
    {
        var authToken = new JwtSecurityToken(cookie.Value);
        var authJwtId = authToken.Claims.First(c => c.Type == "jti").Value;
        var identityTokenAuthJwtId = identityToken.Claims.First(c => c.Type == "auth_jti").Value;
        if (authJwtId == identityTokenAuthJwtId)
        {
            return true;
        }
        return false;
    }
}

5. Integrate with application logic

That’s it. Once you have verified the Identity token you can use its sub/Subject to identify the user in your system.

Keep reading to make your implementation production ready.


CoreID Client API and Configuration

Functions

init({ config [object], token [string], callback [function] })

Initializes the CoreID client, must be called before start().

var config = {};
var myCallback = function(data) {};

coreid_client.init({
  config,
  'YOUR TOKEN HERE',
  myCallback
});

start()

Shows the CoreID client to the user.

coreid_client.start();

close()

Hides the CoreID client from the user.

coreid_client.close();

Configuration

token - String, undefined

The secret sauce!

See the this section for information on how to generate your auth token.

token: '😎✌️🏽'

callback - Function, undefined

This function will be invoked by the client at the end of transactions, both for success and fail or in case of an error.

// a basic example
callback: function(data) {
  if (data.success === true) {
    // sweet! let's validate and keep this token for whatever
    $.post('api/token/validate', data.token, handleSuccess, handleError);
  } else if (data.type === 'failed') {
    console.log('authentication failed', data.errorMessage);
  } else if (data.type === 'cancelled') {
    console.log('user closed the app');
  } else if (data.type === 'error') {
    console.log('an error occurred', data.errorMessage);
  }
}

The callback receives an object parameter that can have the following properties

// A successful transaction object would look like this
{
  success: true,          // always exists if authentication succeeded
  token: '#####',         // JWT that contains identity token, validate this!
  provider: 'se-bankid',  // provider that user authenticated with
  type: 'authenticated',  // transaction type
  transactionId: '####'   // is present for most of the providers, use this
                          //   as a reference when contacting Assently Support
}

// An unsuccessful transaction object
{
  type: 'failed',         // if authentication failed
  provider: 'se-bankid',  // provider used
  errorMessage: ''        // information about the possible error
}

// User closed or cancelled CoreID client,
// can happen after authentication is successful
{
  type: 'cancelled',
  errorMessage: 'USER_UI_CANCEL'
}

// An error occurred, which usually indicates
// a wrong configuration
{
  type: 'error',
  errorMessage: '' // details about the error,
  success: false
}

config.allowedEids - String[], ['*']

This option allows you to define which eID Providers you want to enable.

The default value ['*'] will enable all providers.

[
  '*',                // All
  'fi-mv',            // Finnish Mobiilivarmenne
  'fi-tupas',         // Finnish Tupas
  'fi-vrk',           // Finnish VRK
  'no-bankid',        // Norwegian BankID
  'no-bankid-mobile', // Norwegian BankID mobile
  'se-bankid',        // Swedish BankID
  'se-telia-osif'     // Swedish Telia
  'dk-nemid'          // Danish NemID
]

Note that you need to have at least the same eIDs in your token since token parameters define authorization to the CoreID API.

config.location - String, undefined

This option configures the default country view when starting the client.

Overridden by config.provider.

If undefined the user will first be presented with a view to select country.

'se' // default view will display the Swedish providers
'fi' // ... Finnish providers
'no' // ... Norwegian providers
'dk' // ... Danish providers

config.mode - String, undefined

Sets the mode. Depending on the mode only to that mode available eID’s will be shown to the user.

'auth' // Authentication mode

config.provider - String, undefined

Sets the default view to the specific provider, overrides default view set by the location option.

'fi-mv'            // Finnish Mobiilivarmenne
'fi-tupas'         // Finnish Tupas
'fi-vrk'           // Finnish VRK
'no-bankid'        // Norwegian BankID
'no-bankid-mobile' // Norwegian BankID mobile
'se-bankid'        // Swedish BankID
'se-telia-osif'    // Swedish Telia
'dk-nemid'         // Danish NemID

config.providerSettings - Object, undefined

This object allows for provider-specific settings, note that not all providers have this option.

Available configurations:

{
  'se-bankid': {
    // if set to false the client will not try to open the native Swedish BankID app.
    // there is an event emitted with all the info you need,
    // see separate section
    autoStart: true, // default
    // customize the 'redirect'-parameter to Swedish BankID app
    // see Swedish BankID's documentation for more information
    redirectUrl: 'someURI'
  },
  'fi-tupas': {
    // if set, will sort Tupas banks alphabetically, in ascending or descending order
    // if not set, will retain its original order
    sort: 'asc', // or 'desc'
    // use include to specify exactly which banks you want to be available
    // 'include' will make sure the client only ever lists your selected banks
    // for a list of banks and their IDs, see below
    include: [''],
    // use exclude to specify banks to be excluded
    // this option will be ignored if include-option is specified
    exclude: [''],
  },
  'dk-nemid': {
    // NemID does not provide a National ID Number (CPR) in their response, 
    // only a PID (serial number for the e-ID). However they have a service to validate CPR. 
    // To use it you can either add the CPR to config.providerSettings if you know it beforehand, 
    // or make CoreID prompt the user for it before authenticating.
    // The validated CPR will then be included in the CoreID response.
    // CPR Format: DDMMYYSSSS
    cpr: "", 
    cprPrompt: false,
  }
}

Tupas banks:

[
  { Id: "08ACDDE6-2C38-418B-ACC7-67CEF0FD24A8", BankName: "Nordea"},
  { Id: "5A57F571-C625-46D8-A721-7F23CBF0A9AE", BankName: "Danske Bank"},
  { Id: "4885E8D2-C6AC-4732-A3FF-132C4CA9977B", BankName: "Aktia "},
  { Id: "6C583D7B-1C6F-4CBC-9BE9-FA9C26CDD4F1", BankName: "S-Pankki"},
  { Id: "F0EA5D03-E63D-4A0D-84DC-EFEA0FA91306", BankName: "LähiTapiola"},
  { Id: "916194F1-A31A-4DBD-B481-EDDD1F5A311D", BankName: "Handelsbanken"},
  { Id: "1BD11C49-65BF-4DA3-B609-60414EBD8F1F", BankName: "OP"},
  { Id: "8D6C10E6-8C82-4FD2-B55E-E881DA7411B9", BankName: "Säästöpankki"},
  { Id: "2625E44A-3E08-4323-8B4E-D4E0AD1C2615", BankName: "POP Pankki"},
  { Id: "F82E50A2-A778-44CA-827C-6B062477267C", BankName: "Ålandsbanken"}
]

config.showTitle - Boolean, true

showTitle: true

Setting to show the title inside the frame. Defaults to true.

Events

The client also emits some events via PostMessage that developers can subscribe to.

All events are of type MessageEvent and are dispatched at the target window, subscribe like so:

window.addEventListener('message', function(e) {
  // check e.data.type
});

None of these events are required to be handled by the developer, they are provided for your convenience.

bankId-startClient

MessageEvent {
  data: {
    type: 'bankId-startClient', // event type
    autoStartToken: 'TOKEN',    // needed to start the app correctly
    transactionId:  'guid'      // Assently generated transaction id
  }
}

This event fires when the Swedish BankID app is to be opened.

Contains data to allow developers to start the Swedish BankID app by their own accord.

Technical Details

The client is 100% JavaScript and uses XMLHttpRequests and embeds via an iframe.

Test

The test client will target the test environment of our API and the providers (if applicable).

Make sure to use your test account secrets.

Please refer to each providers documentation on how to test authentication with a specific provider.

<script src="https://coreid-test.assently.com/embed/coreid.js"></script>

Production

Only real persons or subjects can authenticate.

Make sure to use your production secrets.

<script src="https://coreid.assently.com/embed/coreid.js"></script>

Message formats

We use JWT (JSON Web Tokens) for secure communication between our server and your clients.

Localization

The client is localized in the following languages:

  • English
  • Finnish
  • Norwegian
  • Swedish

Security

All traffic is encrypted via SSL/TLS.

Information is sent via JSON web tokens (JWT) encrypted with HS256.

Messages are decoded and verified with shared secrets.

The JWT Auth Token

JWT Basics

Take a couple of minutes and read a little bit at https://jwt.io/introduction/.

JWT Libraries

Find a library at https://jwt.io/#libraries or google a library that supports your platform.

Create the JWT

Use the library to define your claims, specify that you want to use HMAC SHA256 and sign it with the auth secret provided by Assently.

Claims

There are 7 claims that are required, e.g.:

{
  "jti": "3bfae357-c056-4567-b15d-ca657fbdg866", //A unique token identifier 
  "iss": "acme", //The customer account name (as issued by Assently)
  "aud": [
    "se-bankid",
    "fi-mv"
  ],// see the description of the claim below
  "iat": 1467217112,//Identifies the time at which the JWT was issued. 
  "exp": 1467218912, //Identifies the expiration time on or after which the JWT is not accepted for processing. 
  "hst": "https://acme.com", //The URL of the host including scheme (and if differs from default, port). 
  // Custom display names must be registered with Assently beforehand
  // Valid displaynames are
  // "Assently" for production
  // "Test av Mobilt BankID" for test
  "dnm": "Acme" //see description below
}

Descriptions for each claim can be found below.

“jti”

Name
JWT id

Description
A unique token identifier

Format
GUID

Example
"3bfae357-c056-4567-b15d-ca657fbdg866"

Mandatory
Yes

“iss”

Name
Issuer

Description
The customer account name (as issued by Assently)

Example
"acme"

Mandatory
Yes

“aud”

Name
Audience

Description
Should contain the eID Providers you want your users to choose from.

Note: Make sure the eID’s in the token at a minimum includes the “allowedEids” configuration in the client.

Available eID’s:

  • all - All available eID’s
  • se - All Swedish eID’s
  • se-bankid - Swedish BankID
  • se-telia-osif - Swedish Telia
  • fi - All Finnish eID’s
  • fi-tupas - Finnish Tupas
  • fi-mv - Finnish Mobiilivarmenne
  • fi-vrk - Finnish VRK
  • no - All Norwegian eID’s
  • no-bankid - Norwegian BankID
  • no-bankid-mobile - Norwegian BankID on mobile
  • dk - All Danish eID’s
  • dk-nemid - Danish NemID

If using multiple eID’s, the “aud” value is an array of strings. If using a single eID the “aud” value can be a single string value.

Example
["se_bankid", "fi-mv"]

Mandatory
Yes

“iat”

Name
Issued at

Description
Identifies the time at which the JWT was issued.

Format
Unix timestamp

Example
1467217112

Mandatory
Yes

“exp”

Name
Expiration time

Description
Identifies the expiration time on or after which the JWT is not accepted for processing.

Format
Unix timestamp

Example
1467218912

Mandatory
Yes

“hst”

The host that is using the service.

Name
Embed host

Description
The URL of the host including scheme (and if differs from default, port).

Format
URL

Example
"https://www.acme.com"

Mandatory
Yes

“dnm”

Name
Display name

Description
The text (usually company name) to be displayed on the end user’s display during authentication.

Note that a custom display name must be registered with Assently in advance. If no display name is registered, “Assently” will be used as default.

In test environment with se-bankid the display name must be specified “Test av Mobilt BankID”.

Example
"Acme"

Mandatory
Only for se-bankid and fi-mv

The JWT Identity Token

When a user has successfully authenticated you will receive a JWT in the callback.

  1. Verify the signature of the token

    To be sure nothing has been tampered with, you must verify the signature of the token with a shared secret.

    HMACSHA256(
      base64(header) + '.' + base64(payload),
      secret
    )
    
  2. Validate the claims of the token

    If any of these claims are invalid, you must reject the JWT.

    iss
    Should match the hostname of the embed script path.

    aud
    Should match your issuer name provided by Assently

    exp
    Must be in the future. The value will be 60 minutes in the future from the time it is generated.

  3. Done!

    The JWT payload contains claims regarding who the authenticated subject is.

    How you use this information is up to you.

“sub”

Identifier of the subject

Name
Subject

Description
Can be a national id number, birthdate or phone number.

Example
"19800101"

Mandatory
Yes

“sub.national_id”

The subjects’ national id number.

Name
National ID

Description
The format can vary depending on eID Provider.

Example
"198001011234"

Mandatory
No

“sub.family_name”

Name
Family name

Description
Last name, surname, or family name of the subject.

Example
"Miller"

Mandatory
No

“sub.given_name”

Given name of the subject.

Name
Given name

Description
Some providers also include middle name(s).

Example
"Frank"

Mandatory
No

“sub.full_name”

Full name of the subject

Name
Full name

Description
Includes first name(s) and last name(s).

Example
"Frank Miller"

Mandatory
No

“provider”

Name
Provider

Description The name of the eID Provider that was used to conduct the authentication.

Example "se-bankid"

Mandatory Yes

“provider.data”

Name
Provider data

Description
All personal information related to the subject as received from the eID Provider. This is usually an x.509 certificate that we send along in its raw form encoded as a base64 string.

Format
base64 encoded string

Mandatory
Yes

“jti”

Name
JWT id

Description
The unique identifier of the token.

Example
"66619e7a-e34b-4f76-85df-71634328d3g1"

Mandatory Yes

“iss”

Name
Issuer

Description
The token issuer.

Example
"coreid-test.assently.com" "coreid.assently.com"

Mandatory Yes

“aud”

The intended receiver of the token.

Name
Audience

Description
Contains your customer account name.

Example
"some-company-name"

Mandatory
Yes

“iat”

Name
Issued at

Description
Identifies the time at which the JWT was issued.

Format
Unix timestamp

Example
1466429950

Mandatory Yes

“exp”

Name
Expiration Time

Description
Identifies the expiration time on or after which the JWT is not accepted for processing.

Format
Unix timestamp

Example
1466433550

Mandatory
Yes

“auth_jti”

The JWT id from the auth token used in the same session.

Name
Auth Token JWT id

Description
This claim can be used for comparison with the “jti” claim in the auth token. A match verifies that the identity received is related to the original request.

Example
"3bfae357-c056-4567-b15d-ca657fbdg866"

Mandatory
Yes

Supported eID Providers

eID Provider Country
Telia Sweden
BankID Sweden
Tupas Finland
Mobiilivarmenne Finland
VRK Finland
BankID Norway
BankID Mobile Norway
NemID til Private (POCES) Denmark
NemID Medarbejdersignatur (MOCES) Denmark

Authenticating in a test-environment

Test Environment

The CoreID Test Environment connects with the different eID Providers’ test services. You have the option to use to this environment if you want to try out one or more eID Provider using test certificates. Since each eID Provider have different ways of authenticating users (software, mobile, etc.) they way to get a hold of test certificates are also specific to each eID Provider. Swedish BankID (Svenskt BankID)

Swedish BankID

To test Swedish BankID you need to download a test certificate at https://demo.bankid.com.

The easiest approach is to go to https://demo.bankid.com, Choose “Log in with personal code” -> “Generate code” and follow the steps. You’ll then be able to set up BankID for testing on your computer.

Certificates are available both for mobile and computer use. Instructions on how to install the BankID software and the test certificate are found at https://www.bankid.com/bankid-i-dina-tjanster/rp-info.

Note that the claim “dnm” (Display Name) in the Auth Token has to be set to "Test av Mobilt BankID" in the test environment.

Swedish Telia

Telia uses a software called Net iD that can be downloaded at https://eid.trust.telia.com/Klient/H%C3%A4mtaNetiD.aspx.

Get test certificates at https://eid.trust.telia.com/Testcertifikat/Teliae-legmjukt.aspx.

Net iD works in IE in Windows.