From 7d7ff345db21829411b1d5f09ca478f5e922c6dc Mon Sep 17 00:00:00 2001 From: Mart Aarma Date: Mon, 14 Sep 2026 13:19:43 +0300 Subject: [PATCH 1/5] Add guide for adding Web eID for Mobile support to an existing integration Add a short section to the README that lists only what an application with a working regular Web eID integration has to change or add for the mobile authentication flow, naming the example files that implement each step. Digital signing is noted as not covered by the PHP library or example. Signed-off-by: Mart Aarma Co-authored-by: Sander Kondratjev --- README.md | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index ffc4773..3416b0d 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ More information about the Web eID project is available on the project [website] # Quickstart -Complete the steps below to add support for secure authentication with eID cards to your PHP web application back end. Instructions for the front end are available [here](https://github.com/web-eid/web-eid.js). +Complete the steps below to add support for secure authentication with eID cards to your PHP web application back end. Instructions for the front end are available [here](https://github.com/web-eid/web-eid.js). If your application already uses Web eID and you only need to add the mobile flow, see [Adding Web eID for Mobile support to an existing integration](#adding-web-eid-for-mobile-support-to-an-existing-integration). A PHP web application that uses Composer to manage packages is needed for running this quickstart. @@ -188,7 +188,7 @@ class Auth ### Issuing challenge nonces for Web eID for Mobile -The `POST /auth/mobile/init` endpoint initiates authentication flows that use **Web eID token format v1.1**. It generates a challenge nonce and returns a deep link URI that embeds a base64-encoded payload containing the challenge nonce, the login endpoint URL and whether the mobile application should include the signing certificate information in the authentication token. The mobile application opens the deep link, signs the challenge and posts the `web-eid:1.1` authentication token to the `POST /auth/mobile/login` endpoint, which validates it with the same `AuthContext::authenticate()` method that is used in the regular flow. See the full implementation in `example/src/MobileAuth.php`. +The `POST /auth/mobile/init` endpoint initiates mobile authentication. Authentication-only responses use `web-eid:1.0`; requesting signing certificate information uses `web-eid:1.1`. It generates a challenge nonce and returns a deep link URI that embeds a base64-encoded payload containing the challenge nonce, the login endpoint URL and whether the mobile application should include the signing certificate information in the authentication token. The mobile application opens the deep link and returns the authentication token in the browser login page URL fragment. The page posts the token to `POST /auth/mobile/login`, which validates it with the same `AuthContext::authenticate()` method that is used in the regular flow. See the full implementation in `example/src/MobileAuth.php`. ```php final class MobileAuth @@ -229,7 +229,7 @@ The deep link base URL and whether the signing certificate is requested are conf ## 6. Implement authentication -Authentication consists of calling the `validate()` method of the authentication token validator. In the updated implementation, the authentication logic is centralized in `AuthContext`, which is used by both `Auth` for the `web-eid:1.0` authentication flow and `MobileAuth` for the `web-eid:1.1` authentication flow. The internal implementation of the validation process is described in more detail below and in the [Web eID system architecture document](https://github.com/web-eid/web-eid-system-architecture-doc#authentication-1). +Authentication consists of calling the `validate()` method of the authentication token validator. In the updated implementation, the authentication logic is centralized in `AuthContext`, which is used by both `Auth` for desktop authentication and `MobileAuth` for mobile authentication. Both flows use `web-eid:1.0` for authentication only; mobile responses that include signing certificate information use `web-eid:1.1`. The internal implementation of the validation process is described in more detail below and in the [Web eID system architecture document](https://github.com/web-eid/web-eid-system-architecture-doc#authentication-1). ```php use web_eid\web_eid_authtoken_validation_php\authtoken\WebEidAuthToken; @@ -331,9 +331,21 @@ Note that successful token validation only establishes *who* the user is; it doe See the complete example in the `example` directory. +## Adding Web eID for Mobile support to an existing integration + +Reuse your existing challenge nonce generator and store, trusted CA configuration, token validation and authorization logic. The mobile flow adds an App Link/Universal Link that opens the RIA DigiDoc app and a login page that receives the response in its URL fragment and posts the token to your back end. Authentication-only responses use `web-eid:1.0`; requesting a signing certificate with `getSigningCertificate=true` requires a validator that supports `web-eid:1.1`. The validator configuration stays the same. + +1. Add `POST /auth/mobile/init` to generate and store a challenge nonce and return `authUri`: `https://id.eesti.ee/auth#`, where the payload is Base64-encoded JSON containing `challenge`, `loginUri` and optionally `getSigningCertificate` ([MobileAuth::init()](example/src/MobileAuth.php), routed via `Auth::mobileInit()`). Set `mobile_base_url` in [app.conf.php](example/src/app.conf.php) to `https://id.eesti.ee` for the RIA DigiDoc app; the example defaults to the development scheme `web-eid-mobile://`. Configure `mobile_request_signing_cert` as needed. +2. Serve `GET /auth/mobile/login` at an HTTPS `loginUri` on the validator's configured `origin_url`. Its script must decode the response, handle errors and post `authToken` to the existing login endpoint ([login page](example/tpl/webeid-login.phtml), [payload parser](example/public/js/payload.js)); the example uses a separate `POST /auth/mobile/login` that shares [AuthContext::authenticate()](example/src/AuthContext.php) with desktop login. Retrieve and consume the session's unexpired challenge nonce, validate the token, apply your authorization checks and establish the authenticated session as before. +3. Use `Secure`, `HttpOnly`, `SameSite=Lax` for the pre-authentication session cookie so it accompanies the return from the app ([index.php](example/public/index.php)). Keep CSRF protection on POST endpoints ([AuthContext::assertCsrf()](example/src/AuthContext.php)) and protect the login page against XSS. Callback fragments are untrusted input; the CSRF token alone does not authenticate them. See the architecture document's [security assumptions](https://github.com/web-eid/web-eid-for-mobile-architecture-doc#security-assumptions). +4. Add a mobile login button that calls the init endpoint and opens the returned `authUri` ([front end](example/tpl/index.phtml)). Keep the existing desktop login control. + +Optional mobile signing is not demonstrated by the PHP example; see the [Java](https://github.com/web-eid/web-eid-authtoken-validation-java/tree/web-eid-mobile/example) and [.NET](https://github.com/web-eid/web-eid-authtoken-validation-dotnet/tree/web-eid-mobile/example) examples. + # Table of contents - [Quickstart](#quickstart) + - [Adding Web eID for Mobile support to an existing integration](#adding-web-eid-for-mobile-support-to-an-existing-integration) - [Introduction](#introduction) - [Authentication token format](#authentication-token-format) - [Supported token format versions](#supported-token-format-versions) @@ -420,11 +432,11 @@ The authentication token validation process consists of the following stages: - First, **user certificate validation**: the validator parses the token and extracts the user certificate from the *unverifiedCertificate* field. Then it checks the certificate expiration, purpose and policies. Next it checks that the certificate is signed by a trusted CA and checks the certificate status with OCSP. - Second, **token signature validation**: the validator validates that the token signature was created using the provided user certificate by reconstructing the signed data `hash(origin)+hash(challenge)` and using the public key from the certificate to verify the signature in the `signature` field. If the signature verification succeeds, then the origin and challenge nonce have been implicitly and correctly verified without the need to implement any additional security checks. - Additional validation for **Web eID authentication tokens (format v1.1)**: the token must contain the `unverifiedSigningCertificates` field with at least one signing certificate entry. Each entry's `supportedSignatureAlgorithms` are validated against the set of allowed cryptographic algorithms, hash functions, and padding schemes. For each signing certificate, the following checks are performed: - - The subject must match the subject of the authentication certificate, ensuring both certificates belong to the same user. - - The issuing authority must match that of the authentication certificate, verified via the Authority Key Identifier (AKI) extension. - - The certificate must be within its validity period. - - The certificate must contain the non-repudiation key usage bit required for digital signatures. - - The certificate chain must validate against the configured trusted certificate authorities. + - The subject must match the subject of the authentication certificate, ensuring both certificates belong to the same user. + - The issuing authority must match that of the authentication certificate, verified via the Authority Key Identifier (AKI) extension. + - The certificate must be within its validity period. + - The certificate must contain the non-repudiation key usage bit required for digital signatures. + - The certificate chain must validate against the configured trusted certificate authorities. The website back end must look up the challenge nonce from its local store using an identifier specific to the browser session, to guarantee that the authentication token was received from the same browser to which the corresponding challenge nonce was issued. The website back end must guarantee that the challenge nonce lifetime is limited and that its expiration is checked, and that it can be used only once by removing it from the store during validation. @@ -587,6 +599,9 @@ The Web eID for Mobile authentication flow is configured with the following addi - `mobile_base_url` – the base URL used for building the mobile authentication deep link, `web-eid-mobile://` by default; - `mobile_request_signing_cert` – whether the mobile application is asked to include the signing certificate information (`unverifiedSigningCertificates`) in the authentication token, `false` by default. + +The example files that implement the mobile flow are listed step by step in *[Adding Web eID for Mobile support to an existing integration](#adding-web-eid-for-mobile-support-to-an-existing-integration)*. + Point your Apache web server Document Root to `/example/public` folder. # Dependency versioning policy From ffe9b9de737c803d10220107b60030d0a05a0ca8 Mon Sep 17 00:00:00 2001 From: Mart Aarma Date: Mon, 14 Sep 2026 13:53:31 +0300 Subject: [PATCH 2/5] Fix CSRF validation for mobile authentication initialization Signed-off-by: Mart Aarma Co-authored-by: Sander Kondratjev --- example/src/MobileAuth.php | 4 +- example/src/Pages.php | 6 +- tests/example/MobileAuthInitTest.php | 62 +++++++++++++++++++++ tests/example/PagesCsrfTest.php | 48 ++++++++++++++++ tests/example/fixtures/mobile-auth-init.php | 34 +++++++++++ 5 files changed, 149 insertions(+), 5 deletions(-) create mode 100644 tests/example/MobileAuthInitTest.php create mode 100644 tests/example/PagesCsrfTest.php create mode 100644 tests/example/fixtures/mobile-auth-init.php diff --git a/example/src/MobileAuth.php b/example/src/MobileAuth.php index cc83984..7565994 100644 --- a/example/src/MobileAuth.php +++ b/example/src/MobileAuth.php @@ -34,9 +34,7 @@ public function init(): void { header("Content-Type: application/json; charset=utf-8"); - if (!isset($_SESSION["csrf-token"])) { - $_SESSION["csrf-token"] = bin2hex(random_bytes(32)); - } + $this->ctx->assertCsrf(); $challenge = $this->ctx->nonceGenerator()->generateAndStoreNonce(); diff --git a/example/src/Pages.php b/example/src/Pages.php index f2450e0..14fba77 100644 --- a/example/src/Pages.php +++ b/example/src/Pages.php @@ -34,8 +34,10 @@ public function __construct() private function generateCsrfToken() { - // Store token to session - $_SESSION["csrf-token"] = bin2hex(random_bytes(32)); + if (!isset($_SESSION["csrf-token"])) { + // Store token to session + $_SESSION["csrf-token"] = bin2hex(random_bytes(32)); + } return $_SESSION["csrf-token"]; } diff --git a/tests/example/MobileAuthInitTest.php b/tests/example/MobileAuthInitTest.php new file mode 100644 index 0000000..575067b --- /dev/null +++ b/tests/example/MobileAuthInitTest.php @@ -0,0 +1,62 @@ + [[], ['csrf-token' => 'expected'], false], + 'incorrect token' => [['X-CSRF-TOKEN' => 'wrong'], ['csrf-token' => 'expected'], false], + 'missing session token' => [['X-CSRF-TOKEN' => 'expected'], [], false], + 'matching token' => [['X-CSRF-TOKEN' => 'expected'], ['csrf-token' => 'expected'], true], + ]; + } + + #[DataProvider('csrfRequests')] + public function testInitializationRequiresCsrfToken(array $headers, array $session, bool $accepted): void + { + // A rejected request must not replace an outstanding authentication challenge. + $session['web-eid-challenge-nonce'] = 'existing challenge'; + $process = proc_open( + [PHP_BINARY, __DIR__ . '/fixtures/mobile-auth-init.php'], + [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], + $pipes + ); + self::assertIsResource($process); + fwrite($pipes[0], json_encode(['headers' => $headers, 'session' => $session], JSON_THROW_ON_ERROR)); + fclose($pipes[0]); + $output = stream_get_contents($pipes[1]); + $errors = stream_get_contents($pipes[2]); + fclose($pipes[1]); + fclose($pipes[2]); + self::assertSame(0, proc_close($process), $errors); + self::assertSame('', $errors); + $result = json_decode($output, true, 512, JSON_THROW_ON_ERROR); + $body = json_decode($result['body'], true, 512, JSON_THROW_ON_ERROR); + + if (!$accepted) { + self::assertSame(405, $result['status']); + self::assertSame(['error' => 'CSRF token missing or invalid'], $body); + self::assertSame($session, $result['session']); + return; + } + + self::assertSame(200, $result['status']); + self::assertSame($session['csrf-token'], $result['session']['csrf-token']); + self::assertStringStartsWith('https://mopp.ria.ee/auth#', $body['authUri']); + $payload = json_decode(base64_decode(explode('#', $body['authUri'], 2)[1]), true, 512, JSON_THROW_ON_ERROR); + self::assertSame('https://example.com/auth/mobile/login', $payload['loginUri']); + self::assertFalse($payload['getSigningCertificate']); + $nonce = unserialize($result['session']['web-eid-challenge-nonce'], [ + 'allowed_classes' => [ChallengeNonce::class, \DateTime::class], + ]); + self::assertInstanceOf(ChallengeNonce::class, $nonce); + self::assertSame($nonce->getBase64EncodedNonce(), $payload['challenge']); + } +} diff --git a/tests/example/PagesCsrfTest.php b/tests/example/PagesCsrfTest.php new file mode 100644 index 0000000..20e05e7 --- /dev/null +++ b/tests/example/PagesCsrfTest.php @@ -0,0 +1,48 @@ +renderPageToken('login'); + self::assertMatchesRegularExpression('/^[a-f0-9]{64}$/', $firstToken); + self::assertSame($firstToken, $_SESSION['csrf-token']); + + // Another tab or the mobile callback must not invalidate the first page. + self::assertSame($firstToken, $this->renderPageToken('login')); + self::assertSame($firstToken, $this->renderPageToken('mobileLoginView')); + self::assertSame($firstToken, $_SESSION['csrf-token']); + } finally { + if ($previousSession === null) { + unset($_SESSION); + } else { + $_SESSION = $previousSession; + } + } + } + + private function renderPageToken(string $action): string + { + ob_start(); + try { + $page = new \Pages(); + $page->$action(); + unset($page); // Pages renders the outer template in its destructor. + $html = ob_get_contents(); + } finally { + ob_end_clean(); + } + self::assertSame(1, preg_match('/ http_response_code(), + 'body' => $body, + 'session' => $_SESSION, + ], JSON_THROW_ON_ERROR); +}); + +$config = Config::fromArray([ + 'origin_url' => 'https://example.com', + 'mobile_base_url' => 'https://mopp.ria.ee', + 'mobile_request_signing_cert' => false, +]); +(new MobileAuth(new AuthContext($config)))->init(); From e97dc40e6171b143f53f0aed8c57ceebdb50d24a Mon Sep 17 00:00:00 2001 From: Mart Aarma Date: Tue, 22 Sep 2026 12:22:52 +0300 Subject: [PATCH 3/5] Fix base URL Signed-off-by: Mart Aarma Co-authored-by: Sander Kondratjev --- tests/example/MobileAuthInitTest.php | 2 +- tests/example/fixtures/mobile-auth-init.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/example/MobileAuthInitTest.php b/tests/example/MobileAuthInitTest.php index 575067b..3fa34f8 100644 --- a/tests/example/MobileAuthInitTest.php +++ b/tests/example/MobileAuthInitTest.php @@ -49,7 +49,7 @@ public function testInitializationRequiresCsrfToken(array $headers, array $sessi self::assertSame(200, $result['status']); self::assertSame($session['csrf-token'], $result['session']['csrf-token']); - self::assertStringStartsWith('https://mopp.ria.ee/auth#', $body['authUri']); + self::assertStringStartsWith('https://id.eesti.ee/auth#', $body['authUri']); $payload = json_decode(base64_decode(explode('#', $body['authUri'], 2)[1]), true, 512, JSON_THROW_ON_ERROR); self::assertSame('https://example.com/auth/mobile/login', $payload['loginUri']); self::assertFalse($payload['getSigningCertificate']); diff --git a/tests/example/fixtures/mobile-auth-init.php b/tests/example/fixtures/mobile-auth-init.php index 88ac827..e70b419 100644 --- a/tests/example/fixtures/mobile-auth-init.php +++ b/tests/example/fixtures/mobile-auth-init.php @@ -28,7 +28,7 @@ function getallheaders(): array $config = Config::fromArray([ 'origin_url' => 'https://example.com', - 'mobile_base_url' => 'https://mopp.ria.ee', + 'mobile_base_url' => 'https://id.eesti.ee', 'mobile_request_signing_cert' => false, ]); (new MobileAuth(new AuthContext($config)))->init(); From 83d1d958899787fa90c62e8bbe466a72dd5aea06 Mon Sep 17 00:00:00 2001 From: Mart Aarma Date: Mon, 19 Oct 2026 19:11:49 +0300 Subject: [PATCH 4/5] Update README MobileAuth example to use assertCsrf() Signed-off-by: Mart Aarma Co-authored-by: Sander Kondratjev --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index 3416b0d..982dede 100644 --- a/README.md +++ b/README.md @@ -201,9 +201,7 @@ final class MobileAuth { header("Content-Type: application/json; charset=utf-8"); - if (!isset($_SESSION["csrf-token"])) { - $_SESSION["csrf-token"] = bin2hex(random_bytes(32)); - } + $this->ctx->assertCsrf(); $challenge = $this->ctx->nonceGenerator()->generateAndStoreNonce(); From 15ad796bab52e579b9d08d9f05d64bcc39ba04e4 Mon Sep 17 00:00:00 2001 From: Mart Aarma Date: Mon, 19 Oct 2026 19:23:02 +0300 Subject: [PATCH 5/5] Post raw authentication token in mobile login like desktop login Align with the Java example: the mobile login page posts the token object directly as the request body instead of wrapping it in {"authToken": ...}, matching POST /validate. Signed-off-by: Mart Aarma Co-authored-by: Sander Kondratjev --- example/src/MobileAuth.php | 9 ++------- example/tpl/webeid-login.phtml | 4 ++-- 2 files changed, 4 insertions(+), 9 deletions(-) diff --git a/example/src/MobileAuth.php b/example/src/MobileAuth.php index 7565994..61a6328 100644 --- a/example/src/MobileAuth.php +++ b/example/src/MobileAuth.php @@ -58,18 +58,13 @@ public function login(): void $this->ctx->assertCsrf(); $this->ctx->assertJsonContentType(); - $json = json_decode(file_get_contents("php://input"), true); - if (!isset($json["authToken"])) { - http_response_code(400); - echo json_encode(["error" => "Missing authToken"]); - return; - } + $authToken = file_get_contents("php://input"); try { $nonce = (new ChallengeNonceStore())->getAndRemove(); $authResult = $this->ctx->authenticate( - json_encode($json["authToken"]), + $authToken, $nonce->getBase64EncodedNonce() ); diff --git a/example/tpl/webeid-login.phtml b/example/tpl/webeid-login.phtml index 20af4ba..7707491 100644 --- a/example/tpl/webeid-login.phtml +++ b/example/tpl/webeid-login.phtml @@ -39,8 +39,8 @@ "Content-Type": "application/json", "X-CSRF-TOKEN": csrfToken }, - body: JSON.stringify({ authToken: authToken }), - credentials: "include" + body: JSON.stringify(authToken), + credentials: "include" }); await checkHttpError(response);