A cross platform Audiobookshelf client for Android and iOS
Dart
Switch OIDC login from external browser to Chrome Custom Tabs
Nathan Poulson5700cfa69a6b
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex 57c5de21..925a969d 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -27,14 +27,19 @@<category android:name="android.intent.category.DEFAULT"/></intent-filter>- <!-- oidc -->- <intent-filter>+ </activity>++ <!-- OIDC callback via Chrome Custom Tab (flutter_web_auth_2) -->+ <activity+ android:name="com.linusu.flutter_web_auth_2.CallbackActivity"+ android:exported="true"+ android:taskAffinity="">+ <intent-filter android:label="flutter_web_auth_2"><action android:name="android.intent.action.VIEW" /><category android:name="android.intent.category.DEFAULT" /><category android:name="android.intent.category.BROWSABLE" />- <data android:scheme="audiobookshelf" android:host="oauth" />+ <data android:scheme="audiobookshelf" /></intent-filter>-</activity><!-- audio_service: background playback and media notification -->diff --git a/lib/screens/login_screen.dart b/lib/screens/login_screen.dartindex 8d0e7fd8..ed34d4d3 100644--- a/lib/screens/login_screen.dart+++ b/lib/screens/login_screen.dart@@ -3,7 +3,6 @@ import 'dart:ui';import 'package:flutter/material.dart';import 'package:package_info_plus/package_info_plus.dart';import 'package:provider/provider.dart';-import 'package:app_links/app_links.dart';import '../providers/auth_provider.dart';import '../services/api_service.dart';import '../services/oidc_service.dart';@@ -41,7 +40,6 @@ class _LoginScreenState extends State<LoginScreen>// OIDC stateOidcConfig? _oidcConfig;bool _isOidcLoading = false;- StreamSubscription? _linkSub;// Custom headers (advanced)bool _showAdvanced = false;@@ -72,59 +70,6 @@ class _LoginScreenState extends State<LoginScreen>_animController.forward();_serverController.addListener(_onServerChanged);_loadVersion();- _initDeepLinkListener();- }-- /// Listen for deep links (audiobookshelf://oauth callback).- void _initDeepLinkListener() {- final appLinks = AppLinks();- _linkSub = appLinks.uriLinkStream.listen((uri) {- debugPrint('[Login] Deep link received: $uri');- if (uri.scheme == 'audiobookshelf' && uri.host == 'oauth') {- _handleOidcCallback(uri);- }- });- }-- /// Handle the OIDC callback URI from deep link.- Future<void> _handleOidcCallback(Uri uri) async {- final oidc = OidcService();- if (!oidc.isWaitingForCallback) {- debugPrint('[Login] No OIDC flow in progress, ignoring callback');- return;- }-- setState(() {- _isOidcLoading = true;- _loginError = null;- });-- final result = await oidc.handleCallback(uri);- if (result != null && mounted) {- final serverText = _serverController.text.trim();- final cleanUrl = serverText.replaceAll(RegExp(r'^https?://'), '');- final fullUrl = '$_protocol$cleanUrl';-- final auth = context.read<AuthProvider>();- final success = await auth.loginWithOidc(- serverUrl: fullUrl,- result: result,- );-- if (mounted) {- setState(() => _isOidcLoading = false);- if (!success) {- setState(() => _loginError = auth.errorMessage ?? 'SSO login failed');- } else if (Navigator.of(context).canPop()) {- Navigator.of(context).pop();- }- }- } else if (mounted) {- setState(() {- _isOidcLoading = false;- _loginError = 'SSO authentication failed. Please try again.';- });- }}Future<void> _loadVersion() async {@@ -137,7 +82,6 @@ class _LoginScreenState extends State<LoginScreen>@overridevoid dispose() {_debounce?.cancel();- _linkSub?.cancel();_animController.dispose();_serverController.dispose();_usernameController.dispose();@@ -302,15 +246,37 @@ class _LoginScreenState extends State<LoginScreen>final cleanUrl = serverText.replaceAll(RegExp(r'^https?://'), '');final fullUrl = '$_protocol$cleanUrl';- final error = await OidcService().startLogin(fullUrl);- if (error != null && mounted) {+ final oidc = OidcService();+ final callbackUri = await oidc.startLogin(fullUrl);+ if (callbackUri == null) {+ if (mounted) setState(() {+ _isOidcLoading = false;+ _loginError = 'SSO login failed or was cancelled';+ });+ return;+ }++ final result = await oidc.handleCallback(callbackUri);+ if (result != null && mounted) {+ final auth = context.read<AuthProvider>();+ final success = await auth.loginWithOidc(+ serverUrl: fullUrl,+ result: result,+ );+ if (mounted) {+ setState(() => _isOidcLoading = false);+ if (!success) {+ setState(() => _loginError = auth.errorMessage ?? 'SSO login failed');+ } else if (Navigator.of(context).canPop()) {+ Navigator.of(context).pop();+ }+ }+ } else if (mounted) {setState(() {_isOidcLoading = false;- _loginError = error;+ _loginError = 'SSO authentication failed. Please try again.';});}- // If no error, we're waiting for the deep link callback.- // _isOidcLoading stays true until callback arrives.}@overridediff --git a/lib/services/oidc_service.dart b/lib/services/oidc_service.dartindex 2121cc75..f72754a3 100644--- a/lib/services/oidc_service.dart+++ b/lib/services/oidc_service.dart@@ -3,8 +3,8 @@ import 'dart:math';import 'package:crypto/crypto.dart';import 'package:flutter/foundation.dart';import 'package:http/http.dart' as http;-import 'package:url_launcher/url_launcher.dart';-import 'dart:io' show Cookie, HttpClient, HttpClientRequest, HttpHeaders;+import 'package:flutter_web_auth_2/flutter_web_auth_2.dart';+import 'dart:io' show HttpClient, HttpHeaders;/// Manages the OIDC/OAuth2 PKCE flow for audiobookshelf SSO login.class OidcService {@@ -39,9 +39,9 @@ class OidcService {_codeChallenge = base64Url.encode(digest.bytes).replaceAll('=', '');}- /// Start the OIDC login flow.- /// Returns null on success (browser opened), or an error string on failure.- Future<String?> startLogin(String serverUrl) async {+ /// Start the OIDC login flow using a Chrome Custom Tab.+ /// Returns the callback [Uri] on success, or null on failure/cancellation.+ Future<Uri?> startLogin(String serverUrl) async {_serverUrl = serverUrl.endsWith('/') ? serverUrl.substring(0, serverUrl.length - 1) : serverUrl;_generatePkce();_state = _generateRandom(16);@@ -58,24 +58,23 @@ class OidcService {debugPrint('[OIDC] Starting auth flow: $authUrl');try {- // Use dart:io HttpClient to properly capture Set-Cookie headers- // (the http package merges them and loses data)+ // Pre-flight request to capture cookies and get the OIDC provider redirect URL.+ // ABS sets a session cookie that links the PKCE challenge to this flow.final client = HttpClient();client.connectionTimeout = const Duration(seconds: 15);+ String? providerUrl;try {final request = await client.getUrl(Uri.parse(authUrl));request.followRedirects = false;final response = await request.close();- // Capture all cookies+ // Capture cookies for the callback requestfinal cookies = response.cookies;for (final cookie in cookies) {_rawCookies.add('${cookie.name}=${cookie.value}');debugPrint('[OIDC] Captured cookie: ${cookie.name}');}-- // Also try raw headerif (_rawCookies.isEmpty) {final rawSetCookie = response.headers[HttpHeaders.setCookieHeader];if (rawSetCookie != null) {@@ -88,41 +87,48 @@ class OidcService {}if (response.statusCode == 302 || response.statusCode == 301) {- final location = response.headers.value(HttpHeaders.locationHeader);- if (location != null && location.isNotEmpty) {- debugPrint('[OIDC] Redirecting to OIDC provider: $location');-- // Drain the response body- await response.drain<void>();-- final uri = Uri.parse(location);- final launched = await launchUrl(uri, mode: LaunchMode.externalApplication);- if (!launched) {- return 'Could not open browser for SSO login';- }- return null; // Success — waiting for callback- }+ providerUrl = response.headers.value(HttpHeaders.locationHeader);await response.drain<void>();- return 'Server did not return a redirect URL';} else {final body = await response.transform(utf8.decoder).join();debugPrint('[OIDC] Unexpected status ${response.statusCode}: $body');- return 'Server returned status ${response.statusCode}';+ _cleanup();+ return null;}} finally {client.close();}++ if (providerUrl == null || providerUrl.isEmpty) {+ debugPrint('[OIDC] Server did not return a redirect URL');+ _cleanup();+ return null;+ }++ debugPrint('[OIDC] Opening Custom Tab for: $providerUrl');++ // Open the OIDC provider in a Chrome Custom Tab. This blocks until the+ // provider redirects back to audiobookshelf://oauth, which the Custom Tab+ // intercepts and returns. Unlike an external browser, Custom Tabs won't+ // be hijacked by PWAs or other apps registered for the provider's domain.+ final resultUrl = await FlutterWebAuth2.authenticate(+ url: providerUrl,+ callbackUrlScheme: 'audiobookshelf',+ );++ debugPrint('[OIDC] Custom Tab returned: $resultUrl');+ return Uri.parse(resultUrl);} catch (e) {- debugPrint('[OIDC] Error starting login: $e');- return 'Failed to start SSO login: $e';+ debugPrint('[OIDC] Error during login: $e');+ _cleanup();+ return null;}}/// Build a Cookie header string from stored cookies.String get _cookieHeader => _rawCookies.join('; ');- /// Handle the callback from the deep link.- /// [uri] is the full audiobookshelf://oauth?code=X&state=Y URI.+ /// Handle the callback URI returned from the Custom Tab./// Returns the user login response (same as /login) or null on failure.Future<Map<String, dynamic>?> handleCallback(Uri uri) async {final code = uri.queryParameters['code'];@@ -156,7 +162,6 @@ class OidcService {debugPrint('[OIDC] Sending ${_rawCookies.length} cookies');try {- // Use dart:io HttpClient for proper cookie handlingfinal client = HttpClient();client.connectionTimeout = const Duration(seconds: 15);@@ -164,7 +169,6 @@ class OidcService {final request = await client.getUrl(Uri.parse(callbackUrl));request.followRedirects = false;- // Attach cookiesif (_rawCookies.isNotEmpty) {request.headers.set(HttpHeaders.cookieHeader, _cookieHeader);}@@ -192,9 +196,6 @@ class OidcService {}}- /// Check if we have an active OIDC flow waiting for callback.- bool get isWaitingForCallback => _state != null && _codeVerifier != null;-/// Clean up after flow completes or is cancelled.void _cleanup() {_codeVerifier = null;diff --git a/pubspec.lock b/pubspec.lockindex b4786195..fb64d644 100644--- a/pubspec.lock+++ b/pubspec.lock@@ -9,38 +9,6 @@ packages:url: "https://pub.dev"source: hostedversion: "2.0.3"- app_links:- dependency: "direct main"- description:- name: app_links- sha256: "5f88447519add627fe1cbcab4fd1da3d4fed15b9baf29f28b22535c95ecee3e8"- url: "https://pub.dev"- source: hosted- version: "6.4.1"- app_links_linux:- dependency: transitive- description:- name: app_links_linux- sha256: f5f7173a78609f3dfd4c2ff2c95bd559ab43c80a87dc6a095921d96c05688c81- url: "https://pub.dev"- source: hosted- version: "1.0.3"- app_links_platform_interface:- dependency: transitive- description:- name: app_links_platform_interface- sha256: "05f5379577c513b534a29ddea68176a4d4802c46180ee8e2e966257158772a3f"- url: "https://pub.dev"- source: hosted- version: "2.0.2"- app_links_web:- dependency: transitive- description:- name: app_links_web- sha256: af060ed76183f9e2b87510a9480e56a5352b6c249778d07bd2c95fc35632a555- url: "https://pub.dev"- source: hosted- version: "1.0.4"archive:dependency: transitivedescription:@@ -225,6 +193,14 @@ packages:url: "https://pub.dev"source: hostedversion: "0.7.12"+ desktop_webview_window:+ dependency: transitive+ description:+ name: desktop_webview_window+ sha256: "57cf20d81689d5cbb1adfd0017e96b669398a669d927906073b0e42fc64111c0"+ url: "https://pub.dev"+ source: hosted+ version: "0.2.3"device_info_plus:dependency: "direct main"description:@@ -379,6 +355,22 @@ packages:description: fluttersource: sdkversion: "0.0.0"+ flutter_web_auth_2:+ dependency: "direct main"+ description:+ name: flutter_web_auth_2+ sha256: "432ff8c7b2834eaeec3378d99e24a0210b9ac2f453b3f7a7d739a5c09069fba3"+ url: "https://pub.dev"+ source: hosted+ version: "5.0.1"+ flutter_web_auth_2_platform_interface:+ dependency: transitive+ description:+ name: flutter_web_auth_2_platform_interface+ sha256: ba0fbba55bffb47242025f96852ad1ffba34bc451568f56ef36e613612baffab+ url: "https://pub.dev"+ source: hosted+ version: "5.0.0"flutter_web_plugins:dependency: transitivedescription: flutter@@ -392,14 +384,6 @@ packages:url: "https://pub.dev"source: hostedversion: "4.7.3"- gtk:- dependency: transitive- description:- name: gtk- sha256: e8ce9ca4b1df106e4d72dad201d345ea1a036cc12c360f1a7d5a758f78ffa42c- url: "https://pub.dev"- source: hosted- version: "2.1.0"html:dependency: transitivedescription:@@ -1092,6 +1076,14 @@ packages:url: "https://pub.dev"source: hostedversion: "2.1.0"+ window_to_front:+ dependency: transitive+ description:+ name: window_to_front+ sha256: "7aef379752b7190c10479e12b5fd7c0b9d92adc96817d9e96c59937929512aee"+ url: "https://pub.dev"+ source: hosted+ version: "0.0.3"xdg_directories:dependency: transitivedescription:diff --git a/pubspec.yaml b/pubspec.yamlindex e6ffa9a8..9b6a6749 100644--- a/pubspec.yaml+++ b/pubspec.yaml@@ -57,7 +57,7 @@ dependencies:#OIDCcrypto: ^3.0.3url_launcher: ^6.2.5- app_links: ^6.1.1+ flutter_web_auth_2: ^5.0.1# Pausing for interruptionsaudio_session: ^0.1.21