Skip to main content
Developer

App2App#

View as Markdown
On this page

BankID with biometrics supports a direct app-to-app based authentication flow, where the user directly jumps in and out of the BankID App, without the merchant app needing to open an in-app browser.

App2App is supported on both iOS and Android, but the platforms have different default recommendations:

Prerequisites

For now we require merchants to supply both:

  1. 1

    The user's NNIN

  2. 2

    Information about the device the merchant's app is installed on.

That information is required so that we can be reasonably sure the flow will start correctly.

This means you cannot currently use this flow for initial user-authentication, and you are required to implement another flow, like authorization code grant (optionally with an app_callback_uri on iOS), for the cases when BankID with biometrics refuses to initiate due to device mismatch. If App2App starts successfully but the app-switch fails, use the manual recovery in step 10.

Steps

[TOC]

1. Register a client with BankID OIDC#

If you don't have a client registered with BankID OIDC⁠ (opens in a new tab) yet, you'll need to register one. Follow the instructions here⁠ (opens in a new tab) to register your app and obtain the necessary client credentials⁠ (opens in a new tab) (client_id and client_secret).

2. Get the BankID OIDC Configuration#

To ensure seamless integration with BankID OIDC and avoid hardcoding specific endpoints in your app, follow these steps to dynamically fetch the OpenID Connect configuration⁠ (opens in a new tab):

  1. 1

    Determine the appropriate configuration URL based on the environment:

    EnvironmentUrl
    Productionhttps://auth.bankid.no/auth/realms/prod/.well-known/openid-configuration⁠ (opens in a new tab)
    Current (public test environment)https://auth.current.bankid.no/auth/realms/current/.well-known/openid-configuration⁠ (opens in a new tab)
  2. 2

    Send an HTTP GET request to the respective configuration URL using your preferred programming language or API tool.

  3. 3

    Capture the response which will contain a JSON document with the configuration. By dynamically fetching the OIDC configuration, your app remains flexible, allowing for future changes or updates to the endpoints without requiring modifications to your code.

3. Get an access token from BankID OIDC#

To obtain an access token from OIDC, follow these steps:

  1. 1

    Retrieve the token endpoint URL token_endpoint dynamically from the OIDC configuration.

  2. 2

    Call the token endpoint URL with your client credentials.

    You can find more detailed information about acquiring access tokens in the BankID OIDC documentation⁠ (opens in a new tab).

  3. 3

    In the scope field, include the following: permissions/app2app and permissions/client. This field specifies the scope of access granted to the token.

Here's an example of a valid request in the current environment:

POST /auth/realms/current/protocol/openid-connect/token HTTP/1.1
Host: auth.current.bankid.no
Content-Type: application/x-www-form-urlencoded
Authorization: Basic <Base64-encoded client id:client secret>

grant_type=client_credentials&scope=permissions/app2app%20permissions/client

Make sure to replace the <Base64-encoded client id:client secret> placeholder in the Authorization header with your actual client credentials.

4. Get the BankID with biometrics OIDC configuration#

To ensure seamless integration and avoid hardcoding specific endpoints in your app, follow these steps to dynamically fetch the BankID with biometrics OpenID Connect configuration⁠ (opens in a new tab):

  1. 1

    Determine the appropriate configuration URL based on the environment:

  2. 2

    Send an HTTP GET request to the respective configuration URL using your preferred programming language or API tool.

  3. 3

    Capture the response which will contain a JSON document with the configuration. By dynamically fetching the OIDC configuration, your app remains flexible, allowing for future changes or updates to the endpoints without requiring modifications to your code.

  4. 4

    To enhance the reliability and performance of your integration, we strongly advise implementing response caching for the OIDC configuration.

5. Register the permission upfront#

To register a permission, follow these steps:

  1. 1

    Construct a permission statement. See the permissions API for detailed information of how to construct the different permissions. Encode the permission statement using URL safe Base64 encoding. Below is an example of a permission statement for a payment:

    const permissionStatement = {
        "nonce": "dW5pcXVlIHZhbHVl", // Must be unique
        "id": "YmFza2V0IGlk", // Your reference
        "payments": [
            {
                "paymentId": "cGF5bWVudCBpZA", // Your reference
                "amount": "123.45",
                "currency": "NOK",
                "creditorName": "Scrooge McDuck"
            }
        ]
    }
    
    // Example implementation of a b64 URL Safe Encoder
    function b64URLSafeEncode(stringData) {
        return btoa(stringData)
            .replace(/\+/g, "-")
            .replace(/\//g, "_")
            .replace(/=/g, "");
    }
    
    b64URLSafeEncode(
        JSON.stringify(
            permissionStatement
        )
    );
    // -> "eyJub25jZSI6ImRXNXBjWFZsSUhaaGJIVmwiLCJpZCI6IlltRnphMlYwSUdsayIsInBheW1lbnRzIjpbeyJwYXltZW50SWQiOiJjR0Y1YldWdWRDQnBaQSIsImFtb3VudCI6IjEyMy40NSIsImN1cnJlbmN5IjoiTk9LIiwiY3JlZGl0b3JOYW1lIjoiU2Nyb29nZSBNY0R1Y2sifV19"
  2. 2

    Send a POST request to the permissions endpoint, providing the access token received in the first step as a bearer token. Include the permission, which is the URL safe Base64 encoding of the permission statement object.

    Intent specifies how the client wants to complete the process using the permission. For the case of the App2App flow, include app2app as the intent.

    You may optionally include the platform parameter (ios or android). It controls whether an app_callback_uri is required and how the BankID app hands control back to your app:

    platformapp_callback_uriReturn mechanism
    ios (or omitted)RequiredThe BankID app switches back via the universal link you supply.
    androidOptionalThe BankID app minimizes itself, bringing your app back to the foreground.

    In both cases you obtain the result by polling once the user returns to your app.

    If you omit app_callback_uri while platform is not android, the request is rejected, since the callback URI is required to switch back to your app on iOS. On Android the BankID app currently does not use app_callback_uri — it minimizes back to your app instead — so you do not need to supply one. You may still include it for forward-compatibility; a future version of the BankID Android app is expected to honor it.

    POST /permissions/v1/ HTTP/1.1
    Host: api.current.aletheia-test.idtech.no
    Content-Type: application/json
    Authorization: Bearer <access token from step 3>
    
    {
      "type": "payment.v1",
      "iat": 1617091752,
      "exp": 1617092652,
      "permission": < URL safe b64 encoded permission statement from step 1 >,
      "intents": [
        "app2app"
      ],
      "loginHint": [
        {
          "scheme": "nnin",
          "value": "<nnin_as_string>"
        }
      ],
      "platform": "ios",
      "app_callback_uri": "https://merchant.app/app_callback"
    }
  3. 3

    On a successful request, you will receive a response body containing a permission ID, a permission token, and a bindingMessage:

    {
      "id": "1.BY.MEKrA-00GVtmvWOCDYQko_fSg93LO5n2rBnlj-X4MQg.BiDEl_CgfakqahcXjLrFet_GGpEkR_W8D-RK4hORBO0",
      "bindingMessage": "Words to display",
      "permissionToken": "eyJhbGciOiJIUzI1NiIsImtpZCI6IjB5Z3hDX3UzQlpPWXlKZ0Y3eDJ0eWtQaTRCTml2cG9KMDBmYjFzTGliUVUiLCJ0eXAiOiJKV1QifQ.eyJleHAiOjE2MTcwOTU3NDQsImlhdCI6MTYxNzA5MjE0NCwicyI6IjA6LTEjOTIzIiwicCI6IkJpREVsX0NnZmFrcWFoY1hqTHJGZXRfR0dwRWtSX1c4RC1SSzRoT1JCTzAiLCJuYmYiOjE2MTcwOTIxNDh9.39GWvNjNMSKKhKOF4t4HcDnZGNJmLmPT3f612z1VKko"
    }

    Retain bindingMessage (camelCase) for display during manual recovery. The /app-authorize response does not return these words.

6. Acquiring Device Information#

We require the following information to perform device-matching

  1. 1

    Device Platform — the literal string ios or android

  2. 2

    Device Manufacturer

  3. 3

    Device model

Field nameJSON field nameValue on iOSValue on Android
Platformpiosandroid
ManufacturermaAppleBuild.MANUFACTURER
Device ModelmoSee belowBuild.MODEL

The values will be formatted in a JSON-document, that will further be encoded in a URL-safe Base64 encoding just like in step 5.

Example document for an iPhone XS

{
    "p": "ios",
    "ma": "Apple",
    "mo": "iPhone11,2"
}

Finding the device model on iOS#

Your device model value must be equivalent to the result of the following Swift-snippet for an app2app to successfully initiate.

import Foundation

/// Returns a model identifier for the current device.
/// e.g. iPhone12,3
func modelIdentifier() -> String {
    var systemInfo = utsname()
    uname(&systemInfo)
    let machineMirror = Mirror(reflecting: systemInfo.machine)
    return machineMirror.children.reduce("") { identifier, element in
        guard let value = element.value as? Int8, value != 0 else { return identifier }
        return identifier + String(UnicodeScalar(UInt8(value)))
    }
}

Finding the device model on Android#

On Android the values are available directly from android.os.Build⁠ (opens in a new tab). Use Build.MANUFACTURER and Build.MODEL as-is, and the literal string android for the platform.

import android.os.Build
import android.util.Base64
import org.json.JSONObject

/**
 * Builds the URL-safe Base64 `device_info` value for the app-authorize request.
 *
 *   p  = "android"
 *   ma = Build.MANUFACTURER   // e.g. "samsung"
 *   mo = Build.MODEL          // e.g. "SM-S916B"
 */
fun deviceInfoParam(): String {
    val json = JSONObject()
        .put("p", "android")
        .put("ma", Build.MANUFACTURER)
        .put("mo", Build.MODEL)
        .toString()

    return Base64.encodeToString(
        json.toByteArray(Charsets.UTF_8),
        Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP,
    )
}

7. Starting the flow#

Make a POST request to the app-authorize endpoint. You can find the endpoint in the BankID with biometrics' OIDC-configuration under the app_authentication_endpoint key.

  • Include the permissionToken obtained from the permission as the login_hint_token in the request to the app-authorize endpoint.
  • In the scope, include the following scopes:
  • Required:
    • openid
  • Optional:
    • profile - to get the user's profile information.
      • Claims: name, given_name, family_name, birthdate, updated_at
    • sub_nnin - to get the user's national identity number (NNIN).
      • Claims: sub_nnin
      • Note: This is only available for clients with explicit access!
    • sub_bankid - to get the user's BankID PID.
      • Claims: sub_bankid
  • Provide device_info as the URL safe Base64 encoded JSON-document of device information as specified in step 6.

Below is an example of a request to the app-authorize endpoint:

POST /oidc/v1/app-authorize HTTP/1.1
Host: oidc.current.aletheia-test.idtech.no
Content-Type: application/x-www-form-urlencoded

client_assertion=<access token from step 3>
&client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer
&login_hint_token=string
&scope=openid
&device_info=<URL safe base64 encoded JSON-document>
&requested_expriy=300

Ensure to replace the string placeholder values with actual data and provide appropriate values for other fields.

After a successful call to the app-authorize endpoint, you will receive the following response:

{
    "authorize_uri": "stringstring", 
    "auth_req_id": "stringstring",
    "expires_in": 300,
    "interval": 3
}
  • authorize_uri is where you send your user from your app.
  • auth_req_id is used to poll for the final token exchange, similarly to CIBA.
  • interval is the polling interval in seconds to be used between each call to the token endpoint.
  • expires_in may be different from the requested value.

A 403 response with error: "access_denied" and error_description: "No matching device found" means App2App can not start from this device. Use another flow, like authorization code grant. For 3DS integrations, see the required ACS CIBA fallback. See the OpenAPI-specification for detailed error codes.

8. Make the user authenticate#

The authorize_uri from the previous step must be opened on the user's device so the BankID app can take over. It must only be opened if the BankID app is installed on the same device. If the app-switch fails after App2App has started, use the manual recovery in step 10.

In all cases you find out when authentication has succeeded by polling, typically triggered when the user returns to your app.

The authorize_uri is a universal link⁠ (opens in a new tab).

Open it using universalLinksOnly⁠ (opens in a new tab), so the link only opens if it resolves to the installed BankID app. If the link is not opened as a universal link, use the manual recovery in step 10.

Once the user has authenticated, the BankID app returns them to your app via the app_callback_uri you registered. Trigger a poll when your app is reopened.

9. Verifying callback URI#

Apps using deep links for app switching are susceptible to interception and misuse, potentially enabling phishing attacks. To reduce this risk and make exploitation significantly harder, we recommend the following measures:

  1. 1

    Include a Secure Identifier in the Callback URL

    • Incorporate a hash derived from a session or app identifier into the callback URL. Using a hash ensures that sensitive identifiers are not transmitted in plaintext, adding an additional layer of security.
  2. 2

    Verify the Callback on Redirection

    • When your app receives the redirect from the BankID app, validate that the callback matches the expected session or device. This step ensures the redirect originated from the correct source and not a malicious attempt.

10. Poll for the result#

Even if an app_callback_uri was used, you must handle a user manually returning to the app and poll for completion to facilitate manual recovery.

Make a POST request to the token endpoint using the CibaTokenRequest schema.

POST /oidc/v1/token HTTP/1.1
Host: oidc.current.aletheia-test.idtech.no
Content-Type: application/x-www-form-urlencoded

client_assertion=<access token from step 3>
&client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer
&grant_type=urn%3Aopenid%3Aparams%3Agrant%2Dtype%3Aciba
&auth_req_id=string

Note: Make sure to replace the placeholders for auth_req_id and the BankID OIDC access token with your actual values.

The token endpoint will respond with a 400 authorization_pending error if the user has not finished authenticating.

If the authentication succeeded you will get a 200 response with the id_token in the response body.

A successful response will have the following structure:

{
    "token_type": "string",
    "expires_in": 0,
    "id_token": "string"
}

We might return other error responses as described in our OpenAPI-specification.

If the user declines the authentication you will get an explicit access_denied error.

11. Validate the ID token#

To ensure the authenticity and integrity of the received ID token, you must perform the following verification:

  • Verify that the token is signed by a key from our JWKS (JSON Web Key Set)⁠ (opens in a new tab) Document. The URI for the JWKS document can be found under the jwks_uri key in the BankID with biometrics OIDC configuration document you retrieved in step 4. You must also verify that the algorithm used is found in the BankID with biometrics OIDC configuration under id_token_signing_alg_values_supported.
  • We recommend verifying these additional properties:
    • iss (issuer) - The issuer of the token must match the issuer in the BankID with biometrics OIDC configuration.
    • aud (audience) - The audience of the token must match your client ID.
    • exp (expiration time) - The token must not be expired.
    • iat (issued at) - The token must not be issued in the future.
    • acr (authentication context class reference) is only relevant if you've asked for forced step up. If relevant must be verified to be the expected value.

Further information on how to validate the ID token can be found in the OpenID Connect Core specification⁠ (opens in a new tab).

Example flow using app2app (the diagram shows iOS; per-platform differences are called out in notes)

sequenceDiagram
    autonumber
    participant MerchantApp as Merchant App
    participant MerchantBackend as Merchant Backend
    participant Backend as BankID Biometrics Backend
    participant BAPP as Authenticating app

    Note left of MerchantBackend: Need to have NNIN of user
    MerchantApp ->> MerchantApp: gatherDeviceInfo 
    MerchantApp ->> MerchantBackend: beginAuth w/ device_info<br/>iOS: {"p": "ios", "ma": "Apple", "mo": "iPhone11,2"}<br/>Android: {"p": "android", "ma": "samsung", "mo": "SM-S916B"}
    MerchantBackend ->> Backend: POST /permissions<br/>{<br/>app_callback_uri: "https://merchant.com/callback",<br/>intents: ["app2app"],<br/>loginHint: [{scheme: "nnin", value: "12345678910"}]<br/>}
    Note over MerchantBackend,Backend: Android: set platform: "android" and<br/>app_callback_uri may be omitted
    Backend ->> MerchantBackend: permissionToken, bindingMessage (retain)
    MerchantBackend ->> Backend: POST /app-authorize<br/>device_info=X&login_hint_token=Y&scope=Z
    break device mismatch
        Backend ->> MerchantBackend: 403 access_denied: No matching device found
        Note left of MerchantBackend: App2App not started<br/>Need to fall back to alternate flow
    end
    Backend ->> MerchantBackend: authorize_uri, auth_req_id=A, interval, expires_in
    MerchantBackend ->> MerchantApp: authorize_uri 
    MerchantApp ->> BAPP: open authorize_uri<br/>iOS: universalLinksOnly<br/>Android: require non-browser (App Links)
    BAPP ->> BAPP: user authenticates
    alt App switch back
        BAPP ->> MerchantApp: iOS: app switch OUT w/ app_callback_uri<br/>Android: BankID app minimizes, merchant app resumes
    else Manual return
        BAPP ->> MerchantApp: User returns manually
        Note right of MerchantApp: Must display bindingMessage
    end
    MerchantApp ->> MerchantBackend: Poll for result
    MerchantBackend ->> Backend: POST /token<br/>auth_req_id=A
    Note right of MerchantBackend: Poll with auth_req_id, interval and expiry
    Backend ->> MerchantBackend: id_token

Was this page helpful?