Phase B: Keycloak OIDC (PKCE) statt Cookie-Session-Login
App-Code: - KeycloakOidcTokenProvider: PKCE-Login via flutter_appauth, Refresh via Refresh-Token aus flutter_secure_storage, Session-Restore beim App-Start, Logout. - AuthSessionEvent als Provider→Bloc-Brücke (LoggedIn/LoggedOut/ SessionExpired) auf einem Broadcast-Stream. - AuthBloc komplett umgebaut: nimmt jetzt den KeycloakOidcTokenProvider statt UserInfoService, mappt eingehende Provider-Events auf eigene Zustände. Authenticated.fromClaims() liest personalnummer + Name aus dem ID-Token-Payload. - LoginPage: kein Browser+Deep-Link mehr — Button feuert LoginRequested, der Provider übernimmt den restlichen Flow. - network_locator: produktiver KeycloakOidcTokenProvider, doppelt registriert (KeycloakOidcTokenProvider für AuthBloc, AuthTokenProvider für Interceptor). - Auth-State trägt zusätzlich personalnummer/displayName/email; das Legacy-User-Objekt + sessionId bleiben temporär drin, damit die alten ERPframe-Services (Phase D) noch kompilieren. Plattform-Setup: - Android: appAuthRedirectScheme=holzleitner in build.gradle.kts, NetworkSecurityConfig erlaubt HTTP zu localhost/10.0.2.2/127.0.0.1. - iOS: holzleitner als URL-Scheme im Info.plist, ATS-Ausnahme für localhost (HTTP-Keycloak im Dev-Setup). Out of scope: - Keine echte App-Run-Smoke — kommt mit dem User-Test. - iOS-pod-install läuft beim ersten 'flutter run ios' automatisch. - Old ERPframe-Services bleiben aktiv und werfen ab jetzt 401 (kein Cookie-Session-Token mehr) — wird in Phase D entfernt.
This commit is contained in:
26
lib/data/network/auth_session_event.dart
Normal file
26
lib/data/network/auth_session_event.dart
Normal file
@ -0,0 +1,26 @@
|
||||
/// Events, die der `KeycloakOidcTokenProvider` über seinen
|
||||
/// Broadcast-Stream auswirft. Der AuthBloc abonniert diesen Stream
|
||||
/// und reagiert mit eigenen Zustands-Übergängen.
|
||||
///
|
||||
/// Bewusst eigene Events (statt direkter Bloc-Aufrufe), damit der
|
||||
/// Token-Provider keine Abhängigkeit auf die Bloc-Schicht braucht.
|
||||
sealed class AuthSessionEvent {
|
||||
const AuthSessionEvent();
|
||||
}
|
||||
|
||||
/// Erfolgreicher Login (frisch oder restauriert).
|
||||
final class AuthLoggedIn extends AuthSessionEvent {
|
||||
const AuthLoggedIn(this.claims);
|
||||
final Map<String, dynamic> claims;
|
||||
}
|
||||
|
||||
/// Sauberer Logout durch den Nutzer.
|
||||
final class AuthLoggedOut extends AuthSessionEvent {
|
||||
const AuthLoggedOut();
|
||||
}
|
||||
|
||||
/// Refresh fehlgeschlagen oder Server lehnt Token ab — die App muss
|
||||
/// zurück zur Login-Page.
|
||||
final class AuthSessionExpired extends AuthSessionEvent {
|
||||
const AuthSessionExpired();
|
||||
}
|
||||
@ -1,48 +1,56 @@
|
||||
/// Endpoint-Konfiguration für das Rust-Backend.
|
||||
///
|
||||
/// Dies ist eine Übergangs-Konfiguration für Phase A der
|
||||
/// Backend-Migration. Sie wird in Phase D durch eine umfassendere
|
||||
/// `LocalDocuFrameConfiguration`-Ablösung ersetzt (oder die bestehende
|
||||
/// Konfiguration wird erweitert).
|
||||
/// Diese Übergangs-Konfiguration für die Backend-Migration wird in
|
||||
/// Phase D durch eine umfassendere Konfigurations-Ablösung verfeinert
|
||||
/// (Build-Time-Flavor pro Stage etc.).
|
||||
///
|
||||
/// **Werte für lokale Entwicklung:**
|
||||
/// * iOS-Simulator + macOS-Host: `http://127.0.0.1:3000`
|
||||
/// * Android-Emulator: `http://10.0.2.2:3000`
|
||||
/// * Echtes Gerät im LAN: `http://<host-IP>:3000`
|
||||
/// * iOS-Simulator + macOS-Host: `http://localhost:...`
|
||||
/// * Android-Emulator: `http://10.0.2.2:...`
|
||||
/// * Echtes Gerät im LAN: `http://<host-IP>:...`
|
||||
///
|
||||
/// Default ist iOS-Simulator-tauglich. Für Android-Build vor dem
|
||||
/// Compile umstellen — eine Auto-Erkennung pro Platform kommt mit der
|
||||
/// Phase-D-Config.
|
||||
/// Default ist iOS-Simulator-tauglich; für Android-Build vor dem
|
||||
/// Compile umstellen oder per Build-Flag injizieren.
|
||||
class BackendConfig {
|
||||
const BackendConfig({
|
||||
required this.apiBaseUrl,
|
||||
required this.keycloakTokenEndpoint,
|
||||
required this.keycloakIssuerUrl,
|
||||
required this.keycloakClientId,
|
||||
required this.keycloakRedirectUrl,
|
||||
});
|
||||
|
||||
/// Basis-URL der Rust-API (kein abschließender Slash).
|
||||
final String apiBaseUrl;
|
||||
|
||||
/// Vollständiger Token-Endpoint des Keycloak-Realms — Format:
|
||||
/// `{issuer}/protocol/openid-connect/token`.
|
||||
final String keycloakTokenEndpoint;
|
||||
/// Realm-Issuer ohne `/.well-known/...`-Suffix —
|
||||
/// `flutter_appauth` hängt das selbst an für die Discovery.
|
||||
/// Beispiel: `http://localhost:8080/realms/holzleitner`.
|
||||
///
|
||||
/// **Achtung:** Keycloak prägt das `iss`-Claim aus dem Hostnamen
|
||||
/// dieser URL. Das Backend erwartet exakt diesen String als
|
||||
/// `KEYCLOAK_ISSUER_URL`. Mismatch → 401 mit `invalid issuer`.
|
||||
final String keycloakIssuerUrl;
|
||||
|
||||
/// Public-Client-Id, die das Backend als `audience` erwartet
|
||||
/// (aktuell `holzleitner-app`).
|
||||
/// Token-Endpoint des Realms — abgeleitet aus dem Issuer.
|
||||
String get keycloakTokenEndpoint =>
|
||||
'$keycloakIssuerUrl/protocol/openid-connect/token';
|
||||
|
||||
/// Public-Client-Id (entspricht der `aud` im Backend-Token).
|
||||
final String keycloakClientId;
|
||||
|
||||
/// Custom-Scheme-Redirect, das in Keycloak als
|
||||
/// `holzleitner://oauth2redirect` whitelisted ist. Muss mit dem
|
||||
/// `appAuthRedirectScheme` in `android/app/build.gradle.kts` und
|
||||
/// dem `CFBundleURLSchemes`-Eintrag in `ios/Runner/Info.plist`
|
||||
/// matchen.
|
||||
final String keycloakRedirectUrl;
|
||||
|
||||
/// Default-Konfiguration für lokale Entwicklung gegen das
|
||||
/// Docker-Compose-Setup (Postgres + Keycloak + Backend).
|
||||
///
|
||||
/// **Achtung Hostname:** Keycloak prägt das `iss`-Claim des Tokens
|
||||
/// aus dem Hostnamen der Token-Endpoint-URL. Das Backend erwartet
|
||||
/// `iss = http://localhost:8080/realms/holzleitner`, deshalb hier
|
||||
/// `localhost` statt `127.0.0.1`. Auf Android-Emulator entsprechend
|
||||
/// `10.0.2.2` setzen.
|
||||
static const BackendConfig localDev = BackendConfig(
|
||||
apiBaseUrl: 'http://localhost:3000',
|
||||
keycloakTokenEndpoint:
|
||||
'http://localhost:8080/realms/holzleitner/protocol/openid-connect/token',
|
||||
keycloakIssuerUrl: 'http://localhost:8080/realms/holzleitner',
|
||||
keycloakClientId: 'holzleitner-app',
|
||||
keycloakRedirectUrl: 'holzleitner://oauth2redirect',
|
||||
);
|
||||
}
|
||||
|
||||
236
lib/data/network/keycloak_oidc_token_provider.dart
Normal file
236
lib/data/network/keycloak_oidc_token_provider.dart
Normal file
@ -0,0 +1,236 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_appauth/flutter_appauth.dart';
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
|
||||
import 'auth_session_event.dart';
|
||||
import 'auth_token_provider.dart';
|
||||
import 'backend_config.dart';
|
||||
|
||||
/// OIDC-Token-Provider gegen Keycloak (PKCE Authorization Code Flow).
|
||||
///
|
||||
/// Verantwortlich für:
|
||||
/// * **Login** über `flutter_appauth` (Browser-Tab → Keycloak →
|
||||
/// RedirectURI `holzleitner://oauth2redirect`).
|
||||
/// * **Token-Refresh** mit dem persistierten Refresh-Token.
|
||||
/// * **Session-Restore** beim App-Start (Refresh-Token aus Secure
|
||||
/// Storage einlesen + sofortigen Refresh anstoßen).
|
||||
/// * **Logout**: lokale Token droppen + Secure Storage säubern.
|
||||
///
|
||||
/// Access-Token und ID-Token-Claims liegen im Speicher (flüchtig),
|
||||
/// der Refresh-Token wird in der Plattform-Secure-Storage abgelegt
|
||||
/// (Keychain / EncryptedSharedPreferences).
|
||||
///
|
||||
/// Events werden über [events] gebroadcastet — der AuthBloc abonniert
|
||||
/// und reagiert. Diese Indirektion vermeidet eine Abhängigkeit auf die
|
||||
/// Bloc-Schicht.
|
||||
class KeycloakOidcTokenProvider implements AuthTokenProvider {
|
||||
KeycloakOidcTokenProvider({
|
||||
required BackendConfig config,
|
||||
required this.issuerUrl,
|
||||
required this.redirectUrl,
|
||||
FlutterAppAuth? appAuth,
|
||||
FlutterSecureStorage? storage,
|
||||
}) : _config = config,
|
||||
_appAuth = appAuth ?? const FlutterAppAuth(),
|
||||
_storage = storage ?? const FlutterSecureStorage();
|
||||
|
||||
final BackendConfig _config;
|
||||
final FlutterAppAuth _appAuth;
|
||||
final FlutterSecureStorage _storage;
|
||||
|
||||
/// Vollständige Issuer-URL ohne `/.well-known/...`-Suffix.
|
||||
/// Beispiel: `http://localhost:8080/realms/holzleitner`.
|
||||
final String issuerUrl;
|
||||
|
||||
/// Redirect-URI, die im Keycloak-Client erlaubt ist und auf das
|
||||
/// Custom-Scheme der App matcht. Beispiel:
|
||||
/// `holzleitner://oauth2redirect`.
|
||||
final String redirectUrl;
|
||||
|
||||
String? _accessToken;
|
||||
DateTime? _expiresAt;
|
||||
String? _refreshToken;
|
||||
Map<String, dynamic>? _idTokenClaims;
|
||||
|
||||
final StreamController<AuthSessionEvent> _events =
|
||||
StreamController<AuthSessionEvent>.broadcast();
|
||||
|
||||
/// Stream der Auth-Events. Wird vom AuthBloc abonniert.
|
||||
Stream<AuthSessionEvent> get events => _events.stream;
|
||||
|
||||
/// Discovery-URL für `flutter_appauth` — wird intern auch geprüft,
|
||||
/// bevor PKCE losläuft.
|
||||
String get _discoveryUrl => '$issuerUrl/.well-known/openid-configuration';
|
||||
|
||||
/// ID-Token-Claims der aktuellen Session, oder `null` wenn nicht
|
||||
/// angemeldet.
|
||||
Map<String, dynamic>? get idTokenClaims => _idTokenClaims;
|
||||
|
||||
bool get isAuthenticated => _accessToken != null;
|
||||
|
||||
/// Triggert den PKCE-Login-Flow. Wirft, wenn der User abbricht oder
|
||||
/// Keycloak einen Fehler liefert.
|
||||
Future<void> login() async {
|
||||
final result = await _appAuth.authorizeAndExchangeCode(
|
||||
AuthorizationTokenRequest(
|
||||
_config.keycloakClientId,
|
||||
redirectUrl,
|
||||
discoveryUrl: _discoveryUrl,
|
||||
scopes: const ['openid', 'profile'],
|
||||
// Lokales Dev-Setup hat HTTP-Keycloak — der Default-iOS-Browser
|
||||
// würde sonst abbrechen. In Produktion (HTTPS) ist das ein
|
||||
// No-Op und kann bleiben.
|
||||
allowInsecureConnections: true,
|
||||
),
|
||||
);
|
||||
|
||||
_applyTokens(
|
||||
accessToken: result.accessToken,
|
||||
refreshToken: result.refreshToken,
|
||||
idToken: result.idToken,
|
||||
expiresAt: result.accessTokenExpirationDateTime,
|
||||
);
|
||||
await _persistRefreshToken();
|
||||
|
||||
_events.add(AuthLoggedIn(_idTokenClaims ?? const <String, dynamic>{}));
|
||||
}
|
||||
|
||||
/// Versucht, eine vorhandene Session aus der Secure Storage zu
|
||||
/// reaktivieren. Liefert `true`, wenn anschließend ein gültiger
|
||||
/// Access-Token verfügbar ist.
|
||||
Future<bool> restoreSession() async {
|
||||
final stored = await _storage.read(key: _refreshTokenStorageKey);
|
||||
if (stored == null || stored.isEmpty) return false;
|
||||
_refreshToken = stored;
|
||||
|
||||
final token = await currentAccessToken();
|
||||
if (token == null) return false;
|
||||
|
||||
_events.add(AuthLoggedIn(_idTokenClaims ?? const <String, dynamic>{}));
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Bricht die Session ab — droppt alle Tokens lokal. Ein
|
||||
/// serverseitiges `endSession` (Keycloak Single-Logout) machen wir
|
||||
/// bewusst nicht: der Refresh-Token läuft beim Server normal aus,
|
||||
/// und der ID-Token-Hint würde uns zwingen, den rohen ID-Token mit
|
||||
/// in der Session zu halten.
|
||||
Future<void> logout() async {
|
||||
_clearSession();
|
||||
await _storage.delete(key: _refreshTokenStorageKey);
|
||||
_events.add(const AuthLoggedOut());
|
||||
}
|
||||
|
||||
@override
|
||||
Future<String?> currentAccessToken() async {
|
||||
final cached = _accessToken;
|
||||
final expiresAt = _expiresAt;
|
||||
final now = DateTime.now().toUtc();
|
||||
|
||||
// Schwellwert 30 s: Pufferzeit gegen Clock-Drift und
|
||||
// mid-flight-Expiry.
|
||||
if (cached != null &&
|
||||
expiresAt != null &&
|
||||
expiresAt.isAfter(now.add(const Duration(seconds: 30)))) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
final rt = _refreshToken;
|
||||
if (rt == null) return null;
|
||||
|
||||
try {
|
||||
final result = await _appAuth.token(
|
||||
TokenRequest(
|
||||
_config.keycloakClientId,
|
||||
redirectUrl,
|
||||
discoveryUrl: _discoveryUrl,
|
||||
refreshToken: rt,
|
||||
scopes: const ['openid', 'profile'],
|
||||
allowInsecureConnections: true,
|
||||
),
|
||||
);
|
||||
_applyTokens(
|
||||
accessToken: result.accessToken,
|
||||
refreshToken: result.refreshToken ?? rt,
|
||||
idToken: result.idToken,
|
||||
expiresAt: result.accessTokenExpirationDateTime,
|
||||
);
|
||||
await _persistRefreshToken();
|
||||
return _accessToken;
|
||||
} on Exception {
|
||||
// Refresh hat nicht funktioniert — Session ist tot, nicht
|
||||
// wiederherstellbar. Aufrufer kriegen null zurück, AuthBloc
|
||||
// bekommt SessionExpired.
|
||||
_clearSession();
|
||||
await _storage.delete(key: _refreshTokenStorageKey);
|
||||
_events.add(const AuthSessionExpired());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
void _applyTokens({
|
||||
required String? accessToken,
|
||||
required String? refreshToken,
|
||||
required String? idToken,
|
||||
required DateTime? expiresAt,
|
||||
}) {
|
||||
_accessToken = accessToken;
|
||||
_refreshToken = refreshToken;
|
||||
_expiresAt = expiresAt?.toUtc();
|
||||
if (idToken != null) {
|
||||
_idTokenClaims = _decodeJwtPayload(idToken);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _persistRefreshToken() async {
|
||||
final rt = _refreshToken;
|
||||
if (rt == null) return;
|
||||
await _storage.write(key: _refreshTokenStorageKey, value: rt);
|
||||
}
|
||||
|
||||
void _clearSession() {
|
||||
_accessToken = null;
|
||||
_expiresAt = null;
|
||||
_refreshToken = null;
|
||||
_idTokenClaims = null;
|
||||
}
|
||||
|
||||
/// Dispose-Hook für Tests / Hot-Restarts.
|
||||
Future<void> dispose() async {
|
||||
await _events.close();
|
||||
}
|
||||
|
||||
static const String _refreshTokenStorageKey =
|
||||
'holzleitner_keycloak_refresh_token';
|
||||
|
||||
/// Dekodiert das Payload-Segment eines JWT. Wirft bei strukturellen
|
||||
/// Auffälligkeiten — Signatur wird **nicht** geprüft (das macht der
|
||||
/// Server bei jedem Request neu).
|
||||
static Map<String, dynamic> _decodeJwtPayload(String token) {
|
||||
final parts = token.split('.');
|
||||
if (parts.length != 3) {
|
||||
throw FormatException('Token-Format unerwartet: ${parts.length} Teile');
|
||||
}
|
||||
String payload = parts[1];
|
||||
// base64url ohne Padding → wieder padden, sonst wirft base64Url.decode.
|
||||
switch (payload.length % 4) {
|
||||
case 0:
|
||||
break;
|
||||
case 2:
|
||||
payload += '==';
|
||||
case 3:
|
||||
payload += '=';
|
||||
default:
|
||||
throw const FormatException('Token-Payload hat ungültige Länge');
|
||||
}
|
||||
final bytes = base64Url.decode(payload);
|
||||
final json = utf8.decode(bytes);
|
||||
final decoded = jsonDecode(json);
|
||||
if (decoded is! Map<String, dynamic>) {
|
||||
throw const FormatException('Token-Payload ist kein JSON-Objekt');
|
||||
}
|
||||
return decoded;
|
||||
}
|
||||
}
|
||||
@ -3,34 +3,34 @@ import 'package:holzleitner_api/holzleitner_api.dart';
|
||||
|
||||
import 'auth_token_provider.dart';
|
||||
import 'backend_config.dart';
|
||||
import 'dev_password_grant_token_provider.dart';
|
||||
import 'holzleitner_api_factory.dart';
|
||||
import 'keycloak_oidc_token_provider.dart';
|
||||
|
||||
/// Registriert das HTTP-/API-Subsystem im globalen GetIt-Locator.
|
||||
///
|
||||
/// Aufruf bewusst nicht im AppBloc-Lifecycle, sondern in `main()` vor
|
||||
/// dem `runApp` — die API-Klassen sind über die gesamte App-Lebensdauer
|
||||
/// stabil und brauchen keine Reaktion auf App-Events.
|
||||
/// stabil.
|
||||
///
|
||||
/// Phase A nutzt die `DevPasswordGrantTokenProvider`-Implementation.
|
||||
/// Phase B wird hier den OIDC-PKCE-Provider einhängen und die
|
||||
/// Dev-Implementation komplett entfernen.
|
||||
/// Phase B: produktiver `KeycloakOidcTokenProvider`. Die alte
|
||||
/// `DevPasswordGrantTokenProvider`-Implementation bleibt im Code (für
|
||||
/// das reine dart-Smoke-Tool, siehe `tool/smoke_test_api.dart`).
|
||||
void registerNetworking({
|
||||
required GetIt locator,
|
||||
BackendConfig config = BackendConfig.localDev,
|
||||
String testfahrerUsername = 'testfahrer',
|
||||
String testfahrerPassword = 'test',
|
||||
}) {
|
||||
locator.registerSingleton<BackendConfig>(config);
|
||||
|
||||
locator.registerSingleton<AuthTokenProvider>(
|
||||
DevPasswordGrantTokenProvider(
|
||||
tokenEndpoint: config.keycloakTokenEndpoint,
|
||||
clientId: config.keycloakClientId,
|
||||
username: testfahrerUsername,
|
||||
password: testfahrerPassword,
|
||||
),
|
||||
final provider = KeycloakOidcTokenProvider(
|
||||
config: config,
|
||||
issuerUrl: config.keycloakIssuerUrl,
|
||||
redirectUrl: config.keycloakRedirectUrl,
|
||||
);
|
||||
// Doppelt registrieren: einmal unter der konkreten Klasse (für
|
||||
// den AuthBloc, der Login/Logout/Restore aufruft) und einmal hinter
|
||||
// dem Interface (für den HTTP-Interceptor).
|
||||
locator.registerSingleton<KeycloakOidcTokenProvider>(provider);
|
||||
locator.registerSingleton<AuthTokenProvider>(provider);
|
||||
|
||||
locator.registerSingleton<HolzleitnerApi>(
|
||||
buildHolzleitnerApi(
|
||||
|
||||
Reference in New Issue
Block a user