Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 24 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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`.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/validate accepts the raw authentication token directly, but mobile /auth/mobile/login expects {"authToken": ...} structure, this should perhaps be clarified?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Aligned with the Java example: the mobile login page now posts the token object directly as the request body, same as /validate, so both


```php
final class MobileAuth
Expand All @@ -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();

Expand All @@ -229,7 +227,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;
Expand Down Expand Up @@ -331,9 +329,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#<payload>`, 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)
Expand Down Expand Up @@ -420,11 +430,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.

Expand Down Expand Up @@ -587,6 +597,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
Expand Down
13 changes: 3 additions & 10 deletions example/src/MobileAuth.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

README MobileAuth code example still contains the old if (!isset($_SESSION[ ... snippet, the example code should be updated as well.


$challenge = $this->ctx->nonceGenerator()->generateAndStoreNonce();

Expand All @@ -60,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()
);

Expand Down
6 changes: 4 additions & 2 deletions example/src/Pages.php
Original file line number Diff line number Diff line change
Expand Up @@ -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"];
}

Expand Down
4 changes: 2 additions & 2 deletions example/tpl/webeid-login.phtml
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
62 changes: 62 additions & 0 deletions tests/example/MobileAuthInitTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php

namespace web_eid\web_eid_authtoken_validation_php\example;

use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use web_eid\web_eid_authtoken_validation_php\challenge\ChallengeNonce;

final class MobileAuthInitTest extends TestCase
{
public static function csrfRequests(): array
{
return [
'missing header' => [[], ['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://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']);
$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']);
}
}
48 changes: 48 additions & 0 deletions tests/example/PagesCsrfTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

namespace web_eid\web_eid_authtoken_validation_php\example;

use PHPUnit\Framework\TestCase;

require_once __DIR__ . '/../../example/src/Template.php';
require_once __DIR__ . '/../../example/src/Pages.php';

final class PagesCsrfTest extends TestCase
{
public function testOpeningAnotherPageKeepsTheFirstPagesCsrfTokenValid(): void
{
$previousSession = $_SESSION ?? null;
$_SESSION = [];
try {
$firstToken = $this->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('/<meta id="csrftoken" name="csrftoken" content="([^"]*)"/', $html, $matches));
return $matches[1];
}
}
34 changes: 34 additions & 0 deletions tests/example/fixtures/mobile-auth-init.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

// Run the real handler in a subprocess because assertCsrf() terminates rejected requests.
require __DIR__ . '/../../../vendor/autoload.php';
require __DIR__ . '/../../../example/src/Config.php';
require __DIR__ . '/../../../example/src/AuthContext.php';
require __DIR__ . '/../../../example/src/MobileAuth.php';

$request = json_decode(stream_get_contents(STDIN), true, 512, JSON_THROW_ON_ERROR);
$_SESSION = $request['session'];

function getallheaders(): array
{
global $request;
return $request['headers'];
}

http_response_code(200);
ob_start();
register_shutdown_function(function (): void {
$body = ob_get_clean();
echo json_encode([
'status' => http_response_code(),
'body' => $body,
'session' => $_SESSION,
], JSON_THROW_ON_ERROR);
});

$config = Config::fromArray([
'origin_url' => 'https://example.com',
'mobile_base_url' => 'https://id.eesti.ee',
'mobile_request_signing_cert' => false,
]);
(new MobileAuth(new AuthContext($config)))->init();