# Implementation guide

This guide describes how to implement the complete OpenID Connect for Identity Assurance (OIDC4IA) authentication flow with ID Check.

> **Preview**
>
> ID Check OIDC4IA is in preview, so it can change. For a stable integration, use [ID Check](https://docs.stoe.no/id-check.md).

## Step 1: Create the PAR request

### 1.1 Generate PKCE values

Generate a `code_verifier` (43-128 character random string) and compute the `code_challenge`:

```javascript
// Generate code_verifier (43-128 characters)
const codeVerifier = generateRandomString(43);

// Compute code_challenge = BASE64URL(SHA256(code_verifier))
const codeChallenge = base64url(sha256(codeVerifier));
```

### 1.2 Generate state and nonce

```javascript
const state = generateRandomString(32);
const nonce = generateRandomString(32);
```

Store these values in the client's session for later verification.

### 1.3 Build the client assertion JWT

The client assertion authenticates the client. See [Authentication](https://docs.stoe.no/id-check/oidc4ia/getting-started/authentication.md) for full details.

**Header:**

```json
{
  "alg": "ES256",
  "kid": "your-key-id",
  "typ": "JWT"
}
```

**Payload:**

```json
{
  "iss": "your_client_id",
  "sub": "your_client_id",
  "aud": "https://{base-url}",
  "exp": 1759835872
}
```

### 1.4 Build the request object JWT

The request object contains the authorisation parameters, including the OIDC4IA `claims` parameter that specifies which verified identity data the client needs.

**Header:**

```json
{
  "alg": "ES256",
  "kid": "your-key-id",
  "typ": "JWT"
}
```

**Payload:**

```json
{
  "iss": "your_client_id",
  "sub": "your_client_id",
  "aud": "https://{base-url}",
  "exp": 1759835872,
  "client_id": "your_client_id",
  "response_type": "code",
  "redirect_uri": "https://your-app.com/callback",
  "scope": "openid",
  "state": "your-state-value",
  "nonce": "your-nonce-value",
  "code_challenge": "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",
  "code_challenge_method": "S256",
  "claims": { ... }
}
```

#### Understanding the OIDC4IA claims request

The `claims` parameter follows the [OpenID Connect for Identity Assurance (OIDC4IA) specification](https://openid.net/specs/openid-connect-4-identity-assurance-1_0.html). The client uses it to request specific verified identity claims and document evidence.

> **Request only what the application needs**
>
> Only include the claims and document details that the application requires. This follows the principle of data minimisation. The application should not request more personal data than necessary for its use case.

The claims request has two main parts:

1. **`verification.evidence`** - Document details to request (e.g., document type, expiry date, issuer)
2. **`claims`** - Identity claims to request (e.g., name, birthdate, nationality)

#### Minimal example

If the client only needs the user's given name, family name, and birthdate (no document details):

```json
{
  "claims": {
    "id_token": {
      "verified_claims": {
        "verification": {
          "trust_framework": { "value": "stoe" }
        },
        "claims": {
          "given_name": { "essential": true },
          "family_name": { "essential": true },
          "birthdate": { "essential": true }
        }
      }
    }
  }
}
```

> **Note**
>
> The `evidence` array is optional. Omit it entirely if the client only needs identity claims and does not need document details (type, expiry date, issuer, etc.).

#### Full example

If the client needs identity claims and document verification details:

```json
{
  "claims": {
    "id_token": {
      "verified_claims": {
        "verification": {
          "trust_framework": { "value": "stoe" },
          "evidence": [
            {
              "type": { "value": "document" },
              "document_details": {
                "type": null,
                "document_number": null,
                "date_of_expiry": null,
                "issuer": null,
                "personal_number": null
              }
            }
          ]
        },
        "claims": {
          "given_name": { "essential": true },
          "family_name": { "essential": true },
          "birthdate": { "essential": true },
          "nationalities": { "essential": true }
        }
      }
    }
  }
}
```

> **Note**
>
> Fields set to `null` in `document_details` indicate that the client wants that data in the response. Omit the fields that the client does not need.

For the complete list of available claims and document details, see [Pushed authorisation request (PAR)](https://docs.stoe.no/id-check/oidc4ia/api/par.md).

### 1.5 Send the PAR request

```http
POST /par HTTP/1.1
Host: {base-url}
Content-Type: application/x-www-form-urlencoded

client_id=your_client_id
&client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer
&client_assertion=eyJhbGciOiJFUzI1NiIsImtpZCI6...
&request=eyJhbGciOiJFUzI1NiIsImtpZCI6...
```

### 1.6 PAR response

```json
{
  "request_uri": "urn:ietf:params:oauth:request_uri:550e8400-e29b-41d4-a716-446655440000",
  "expires_in": 60
}
```

## Step 2: Redirect the user to the authorisation endpoint

Redirect the user to the `authorization_endpoint` from the [OpenID configuration](https://docs.stoe.no/id-check/oidc4ia/api/openid-configuration.md), with the `request_uri`. In production, the authorisation endpoint is `https://start.idverify.bankid.no/auth`:

```
GET https://start.idverify.bankid.no/auth
  ?client_id=your_client_id
  &request_uri=urn:ietf:params:oauth:request_uri:550e8400-e29b-41d4-a716-446655440000
```

The user then completes identity verification (document scanning and facial recognition) in the **BankID app**. On a phone, the URL opens the BankID app, or the ID Check web client if the app is not installed. On a computer, the URL opens the ID Check web client, which shows a QR code for the user to scan with the BankID app.

## Step 3: Handle the callback

After verification, the user comes back to the client's `redirect_uri` with an authorisation code. On a phone, the **BankID app** opens the `redirect_uri`. On a computer, the **ID Check web client** redirects the browser to it:

```
GET https://your-app.com/callback
  ?code=SplxlOBeZQQYbYS6WxSbIA
  &state=your-state-value
  &iss=https%3A%2F%2F{base-url}
```

> **Warning**
>
> Always verify that the `state` matches the value that the client stored in Step 1.2. This prevents cross-site request forgery (CSRF) attacks.

> **Warning**
>
> Always verify that the `iss` parameter matches the expected ID Check issuer URL (RFC 9207). This prevents mix-up attacks where an attacker could redirect authorisation responses from a different authorisation server.

## Step 4: Exchange code for tokens

### 4.1 Build a new client assertion

Create a new client assertion JSON Web Token (JWT), in the same format as in Step 1.3.

### 4.2 Send the token request

```http
POST /token HTTP/1.1
Host: {base-url}
Content-Type: application/x-www-form-urlencoded

client_id=your_client_id
&client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer
&client_assertion=eyJhbGciOiJFUzI1NiIsImtpZCI6...
&grant_type=authorization_code
&code=SplxlOBeZQQYbYS6WxSbIA
&code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
&redirect_uri=https://your-app.com/callback
```

### 4.3 Token response

```json
{
  "id_token": "eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIn0...",
  "access_token": "not_applicable",
  "token_type": "Bearer",
  "expires_in": 900
}
```

## Step 5: Decrypt and validate the ID token

The `id_token` is a JSON Web Encryption (JWE) that contains a signed JWT.

### 5.1 Decrypt the JWE

Use the client's private key to decrypt the JWE. Then extract the signed JWT.

### 5.2 Verify the JWT signature

Fetch the ID Check public keys from the [JSON Web Key Set (JWKS) endpoint](https://docs.stoe.no/id-check/oidc4ia/api/jwks.md) and verify the signature.

### 5.3 Validate claims

Verify the following claims:

| Claim   | Validation                         |
| ------- | ---------------------------------- |
| `iss`   | Must match the ID Check issuer URL |
| `aud`   | Must match the `client_id`         |
| `exp`   | Must not be expired                |
| `iat`   | Must not be in the future          |
| `nonce` | Must match the nonce from Step 1.2 |

### 5.4 Extract verified claims

The user's verified identity data is in the `verified_claims` object. See [ID token](https://docs.stoe.no/id-check/oidc4ia/id-token.md) for the complete structure.

**Example ID token payload:**

```json
{
  "iss": "https://{base-url}",
  "sub": "hashed-subject-id",
  "aud": "your_client_id",
  "exp": 1759835872,
  "iat": 1759832272,
  "auth_time": 1759832272,
  "jti": "e29b7c1e-6b4a-4a3b-9b1a-2f6c8a7d5e10",
  "nonce": "your-nonce-value",
  "acr": "urn:bankid:idcheck",
  "amr": ["face", "user"],
  "verified_claims": {
    "verification": {
      "trust_framework": "stoe",
      "evidence": [
        {
          "type": "document",
          "check_details": [
            {
              "check_method": "vcrypt",
              "result": "success"
            },
            {
              "check_method": "data",
              "organization": "id.politiet.no",
              "result": "valid"
            }
          ],
          "document_details": {
            "type": "passport",
            "document_number": "AB1234567",
            "date_of_issuance": "2020-01-15",
            "date_of_expiry": "2030-01-15",
            "issuer": {
              "country_code": "NOR",
              "name": "Politiet"
            },
            "personal_number": "12345678901"
          }
        }
      ]
    },
    "claims": {
      "given_name": "AASAMUND",
      "family_name": "OESTENBYEN",
      "picture": "data:image/jpeg;base64,/9j/4AAQSkZJRg...",
      "birthdate": "1990-01-15",
      "gender": "male",
      "nationalities": ["NOR"]
    }
  }
}
```

> **Note**
>
> If requested evidence or claims are not available in the ID Check data, the response does not include them. The response only contains data that was successfully retrieved.

## Complete flow summary

```mermaid
sequenceDiagram
    participant Client
    participant IDCheck as ID Check
    participant Web as ID Check web client
    participant BankID as BankID App
    participant User

    Client->>IDCheck: 1. POST /par
    IDCheck-->>Client: 2. request_uri
    Client->>User: 3. Send the user to /auth
    alt On a phone
        User->>BankID: 4. Complete verification
        BankID->>IDCheck: 5. Request authorisation code
        IDCheck-->>BankID: 6. Return authorisation code
        BankID->>Client: 7. Redirect with code
    else On a computer
        User->>BankID: 4. Scan the QR code from the web client, and complete verification
        Web->>IDCheck: 5. Request the redirect when the session ends
        IDCheck-->>Web: 6. Return the redirect with the authorisation code
        Web->>Client: 7. Redirect with code
    end
    Client->>IDCheck: 8. POST /token
    IDCheck-->>Client: 9. Encrypted ID token
    Client->>Client: 10. Decrypt and validate
```

## Next steps

- [Authentication](https://docs.stoe.no/id-check/oidc4ia/getting-started/authentication.md) - Detailed JWT requirements
- [PAR request](https://docs.stoe.no/id-check/oidc4ia/api/par.md) - Full PAR documentation
- [Token request](https://docs.stoe.no/id-check/oidc4ia/api/token.md) - Full token endpoint documentation
- [ID token](https://docs.stoe.no/id-check/oidc4ia/id-token.md) - Complete ID token structure
