Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Add API key login

Barnabasaead53c80a19
diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb
index f4d98bd4..ad8aae18 100644
--- a/lib/l10n/app_en.arb
+++ b/lib/l10n/app_en.arb
@@ -58,6 +58,8 @@
"loginAddHeader": "Add Header",
"loginSelfSignedCertificates": "Self-signed Certificates",
"loginTrustAllCertificates": "Trust all certificates (for self-signed / custom CA setups)",
+ "loginApiKey": "API Key",
+ "loginApiKeyDescription": "Use an admin-generated API key instead of username/password. Useful when token refresh fails for your account.",
"loginWaitingForSso": "Waiting for SSO...",
"loginRedirectUri": "Redirect URI: audiobookshelf://oauth",
"loginOrSignInManually": "or sign in manually",
@@ -1554,6 +1556,7 @@
"authCannotReachServer": "Cannot reach server at {url}",
"@authCannotReachServer": { "placeholders": { "url": { "type": "String" } } },
"authInvalidUsernameOrPassword": "Invalid username or password",
+ "authInvalidApiKey": "Invalid API key",
"authLoginFailedDetail": "Login failed - check your server address and credentials",
"authUnexpectedServerResponse": "Unexpected server response",
"authSsoUnexpectedResponse": "SSO returned an unexpected response",
diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart
index a3de5efb..a53a10b7 100644
--- a/lib/l10n/app_localizations.dart
+++ b/lib/l10n/app_localizations.dart
@@ -422,6 +422,18 @@ abstract class AppLocalizations {
/// **'Trust all certificates (for self-signed / custom CA setups)'**
String get loginTrustAllCertificates;
+ /// No description provided for @loginApiKey.
+ ///
+ /// In en, this message translates to:
+ /// **'API Key'**
+ String get loginApiKey;
+
+ /// No description provided for @loginApiKeyDescription.
+ ///
+ /// In en, this message translates to:
+ /// **'Use an admin-generated API key instead of username/password. Useful when token refresh fails for your account.'**
+ String get loginApiKeyDescription;
+
/// No description provided for @loginWaitingForSso.
///
/// In en, this message translates to:
@@ -7714,6 +7726,12 @@ abstract class AppLocalizations {
/// **'Invalid username or password'**
String get authInvalidUsernameOrPassword;
+ /// No description provided for @authInvalidApiKey.
+ ///
+ /// In en, this message translates to:
+ /// **'Invalid API key'**
+ String get authInvalidApiKey;
+
/// No description provided for @authLoginFailedDetail.
///
/// In en, this message translates to:
diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart
index 794ce603..9021baf5 100644
--- a/lib/l10n/app_localizations_en.dart
+++ b/lib/l10n/app_localizations_en.dart
@@ -173,6 +173,13 @@ class AppLocalizationsEn extends AppLocalizations {
String get loginTrustAllCertificates =>
'Trust all certificates (for self-signed / custom CA setups)';
+ @override
+ String get loginApiKey => 'API Key';
+
+ @override
+ String get loginApiKeyDescription =>
+ 'Use an admin-generated API key instead of username/password. Useful when token refresh fails for your account.';
+
@override
String get loginWaitingForSso => 'Waiting for SSO...';
@@ -4430,6 +4437,9 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get authInvalidUsernameOrPassword => 'Invalid username or password';
+ @override
+ String get authInvalidApiKey => 'Invalid API key';
+
@override
String get authLoginFailedDetail =>
'Login failed - check your server address and credentials';
diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart
index 4872ec83..058d7498 100644
--- a/lib/l10n/app_localizations_zh.dart
+++ b/lib/l10n/app_localizations_zh.dart
@@ -171,6 +171,13 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get loginTrustAllCertificates => '信任所有证书(用于自签名/自定义 CA 配置)';
+ @override
+ String get loginApiKey => 'API 密钥';
+
+ @override
+ String get loginApiKeyDescription =>
+ '使用管理员生成的 API 密钥代替用户名/密码。当账号的令牌刷新失败时很有用。';
+
@override
String get loginWaitingForSso => '正在等待单点登录(SSO)...';
@@ -4357,6 +4364,9 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get authInvalidUsernameOrPassword => 'Invalid username or password';
+ @override
+ String get authInvalidApiKey => 'Invalid API key';
+
@override
String get authLoginFailedDetail =>
'Login failed - check your server address and credentials';
diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb
index dc2c6531..01543883 100644
--- a/lib/l10n/app_zh.arb
+++ b/lib/l10n/app_zh.arb
@@ -58,6 +58,8 @@
"loginAddHeader": "添加请求头",
"loginSelfSignedCertificates": "自签名证书",
"loginTrustAllCertificates": "信任所有证书(用于自签名/自定义 CA 配置)",
+ "loginApiKey": "API 密钥",
+ "loginApiKeyDescription": "使用管理员生成的 API 密钥代替用户名/密码。当账号的令牌刷新失败时很有用。",
"loginWaitingForSso": "正在等待单点登录(SSO)...",
"loginRedirectUri": "重定向 URI: audiobookshelf://oauth",
"loginOrSignInManually": "或手动登录",
diff --git a/lib/providers/auth_provider.dart b/lib/providers/auth_provider.dart
index a598a1eb..073c1560 100644
--- a/lib/providers/auth_provider.dart
+++ b/lib/providers/auth_provider.dart
@@ -327,6 +327,90 @@ class AuthProvider extends ChangeNotifier {
return true;
}
+ /// Login with an admin-generated API key. Skips `/login` entirely - the key
+ /// is just a bearer token. Treated as a legacy token (no refresh) since API
+ /// keys don't expire and don't have a refresh-token counterpart.
+ Future<bool> loginWithApiKey({
+ required String serverUrl,
+ required String apiKey,
+ Map<String, String> customHeaders = const {},
+ AppLocalizations? l,
+ }) async {
+ _errorMessage = null;
+
+ String url = serverUrl.trim();
+ if (!url.startsWith('http://') && !url.startsWith('https://')) {
+ url = 'http://$url';
+ }
+ if (url.endsWith('/')) {
+ url = url.substring(0, url.length - 1);
+ }
+
+ final reachable = await ApiService.pingServer(url, customHeaders: customHeaders);
+ if (!reachable) {
+ _errorMessage = l?.authCannotReachServer(url) ?? 'Cannot reach server at $url';
+ return false;
+ }
+
+ final (user, statusCode) = await ApiService.loginWithApiKey(
+ serverUrl: url,
+ apiKey: apiKey,
+ customHeaders: customHeaders,
+ );
+
+ if (user == null) {
+ _errorMessage = statusCode == 401
+ ? (l?.authInvalidApiKey ?? 'Invalid API key')
+ : (l?.authLoginFailedDetail ?? 'Login failed - check your server address and API key');
+ return false;
+ }
+
+ _serverUrl = url;
+ _accessToken = apiKey;
+ _refreshToken = null;
+ _isLegacyToken = true;
+ _username = user['username'] as String?;
+ _userId = user['id'] as String?;
+ _defaultLibraryId = null;
+ _userJson = user;
+ _serverSettings = null;
+ _customHeaders = customHeaders;
+
+ _fetchServerVersion(url);
+
+ try {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setString('server_url', _serverUrl!);
+ await prefs.setString('token', _accessToken!);
+ await prefs.remove('refresh_token');
+ if (_username != null) await prefs.setString('username', _username!);
+ if (_userId != null) await prefs.setString('user_id', _userId!);
+ if (customHeaders.isNotEmpty) {
+ await prefs.setString('custom_headers', jsonEncode(customHeaders));
+ } else {
+ await prefs.remove('custom_headers');
+ }
+ } catch (_) {}
+
+ try {
+ await UserAccountService().saveAccount(SavedAccount(
+ serverUrl: _serverUrl!,
+ username: _username ?? '',
+ token: _accessToken!,
+ refreshToken: null,
+ userId: _userId,
+ isLegacyToken: true,
+ ));
+ } catch (_) {}
+
+ await HomeWidgetService().clearStats();
+ HomeWidgetService().refreshStats(force: true);
+
+ _isLoading = false;
+ notifyListeners();
+ return true;
+ }
+
/// Login using OIDC callback response data.
/// [result] is the JSON from /auth/openid/callback — same shape as /login response.
///
diff --git a/lib/screens/login_screen.dart b/lib/screens/login_screen.dart
index 43bd17eb..8ca8aae2 100644
--- a/lib/screens/login_screen.dart
+++ b/lib/screens/login_screen.dart
@@ -30,9 +30,11 @@ class _LoginScreenState extends State<LoginScreen>
final _serverController = TextEditingController();
final _usernameController = TextEditingController();
final _passwordController = TextEditingController();
+ final _apiKeyController = TextEditingController();
final _usernameFocus = FocusNode();
bool _obscurePassword = true;
+ bool _obscureApiKey = true;
bool _isConnecting = false;
String _protocol = 'https://';
@@ -99,6 +101,7 @@ class _LoginScreenState extends State<LoginScreen>
_serverController.dispose();
_usernameController.dispose();
_passwordController.dispose();
+ _apiKeyController.dispose();
_usernameFocus.dispose();
for (final (k, v) in _headerControllers) { k.dispose(); v.dispose(); }
OidcService().cancel();
@@ -203,7 +206,11 @@ class _LoginScreenState extends State<LoginScreen>
}
Future<void> _handleLogin() async {
- if (!_formKey.currentState!.validate()) return;
+ final apiKey = _apiKeyController.text.trim();
+
+ // Skip form validation when an API key is supplied — the username
+ // field's required-validator would otherwise block the submit.
+ if (apiKey.isEmpty && !_formKey.currentState!.validate()) return;
// Validate server first if not yet checked
if (!_serverValid) {
@@ -232,13 +239,20 @@ class _LoginScreenState extends State<LoginScreen>
if (k.isNotEmpty && v.isNotEmpty) headers[k] = v;
}
- final success = await auth.login(
- serverUrl: fullUrl,
- username: _usernameController.text.trim(),
- password: _passwordController.text,
- customHeaders: headers,
- l: AppLocalizations.of(context),
- );
+ final success = apiKey.isNotEmpty
+ ? await auth.loginWithApiKey(
+ serverUrl: fullUrl,
+ apiKey: apiKey,
+ customHeaders: headers,
+ l: AppLocalizations.of(context),
+ )
+ : await auth.login(
+ serverUrl: fullUrl,
+ username: _usernameController.text.trim(),
+ password: _passwordController.text,
+ customHeaders: headers,
+ l: AppLocalizations.of(context),
+ );
if (mounted) {
setState(() => _isConnecting = false);
@@ -626,6 +640,39 @@ class _LoginScreenState extends State<LoginScreen>
),
],
),
+ const SizedBox(height: 8),
+ const Divider(height: 1),
+ const SizedBox(height: 8),
+ Text(l.loginApiKey, style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: cs.onSurfaceVariant.withValues(alpha: 0.7))),
+ const SizedBox(height: 4),
+ Text(l.loginApiKeyDescription,
+ style: TextStyle(fontSize: 11, color: cs.onSurfaceVariant.withValues(alpha: 0.4))),
+ const SizedBox(height: 8),
+ TextField(
+ controller: _apiKeyController,
+ obscureText: _obscureApiKey,
+ autocorrect: false,
+ enableSuggestions: false,
+ style: TextStyle(fontSize: 13, color: cs.onSurface),
+ onChanged: (_) => setState(() {}),
+ decoration: InputDecoration(
+ hintText: l.loginApiKey,
+ hintStyle: TextStyle(color: cs.onSurfaceVariant.withValues(alpha: 0.3), fontSize: 13),
+ filled: true,
+ fillColor: cs.surfaceContainerHighest.withValues(alpha: 0.5),
+ border: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide.none),
+ contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
+ prefixIcon: Icon(Icons.vpn_key_rounded, size: 18, color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
+ suffixIcon: IconButton(
+ icon: Icon(
+ _obscureApiKey ? Icons.visibility_outlined : Icons.visibility_off_outlined,
+ size: 18,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.5),
+ ),
+ onPressed: () => setState(() => _obscureApiKey = !_obscureApiKey),
+ ),
+ ),
+ ),
],
// SSO / OIDC button — only shown when server supports it
@@ -1003,6 +1050,7 @@ class _LoginScreenState extends State<LoginScreen>
Widget _buildCredentialFields(ColorScheme cs, TextTheme tt) {
final l = AppLocalizations.of(context)!;
+ final usingApiKey = _apiKeyController.text.trim().isNotEmpty;
return AutofillGroup(
child: Column(
children: [
@@ -1035,50 +1083,52 @@ class _LoginScreenState extends State<LoginScreen>
),
),
- // Username
- _buildInputField(
- controller: _usernameController,
- focusNode: _usernameFocus,
- label: l.loginUsername,
- cs: cs,
- textInputAction: TextInputAction.next,
- autofillHints: const [AutofillHints.username],
- prefixIcon: Icon(Icons.person_outline_rounded, size: 20,
- color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
- validator: (v) {
- if (v == null || v.trim().isEmpty) {
- return l.loginUsernameRequired;
- }
- return null;
- },
- ),
- const SizedBox(height: 14),
-
- // Password
- _buildInputField(
- controller: _passwordController,
- label: l.loginPassword,
- cs: cs,
- obscureText: _obscurePassword,
- textInputAction: TextInputAction.done,
- autofillHints: const [AutofillHints.password],
- onFieldSubmitted: (_) => _handleLogin(),
- prefixIcon: Icon(Icons.lock_outline_rounded, size: 20,
- color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
- suffixIcon: IconButton(
- icon: Icon(
- _obscurePassword
- ? Icons.visibility_outlined
- : Icons.visibility_off_outlined,
- size: 20,
- color: cs.onSurfaceVariant.withValues(alpha: 0.5),
- ),
- onPressed: () {
- setState(() => _obscurePassword = !_obscurePassword);
+ if (!usingApiKey) ...[
+ // Username
+ _buildInputField(
+ controller: _usernameController,
+ focusNode: _usernameFocus,
+ label: l.loginUsername,
+ cs: cs,
+ textInputAction: TextInputAction.next,
+ autofillHints: const [AutofillHints.username],
+ prefixIcon: Icon(Icons.person_outline_rounded, size: 20,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
+ validator: (v) {
+ if (v == null || v.trim().isEmpty) {
+ return l.loginUsernameRequired;
+ }
+ return null;
},
),
- // No validator — ABS allows passwordless accounts
- ),
+ const SizedBox(height: 14),
+
+ // Password
+ _buildInputField(
+ controller: _passwordController,
+ label: l.loginPassword,
+ cs: cs,
+ obscureText: _obscurePassword,
+ textInputAction: TextInputAction.done,
+ autofillHints: const [AutofillHints.password],
+ onFieldSubmitted: (_) => _handleLogin(),
+ prefixIcon: Icon(Icons.lock_outline_rounded, size: 20,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
+ suffixIcon: IconButton(
+ icon: Icon(
+ _obscurePassword
+ ? Icons.visibility_outlined
+ : Icons.visibility_off_outlined,
+ size: 20,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.5),
+ ),
+ onPressed: () {
+ setState(() => _obscurePassword = !_obscurePassword);
+ },
+ ),
+ // No validator — ABS allows passwordless accounts
+ ),
+ ],
const SizedBox(height: 24),
// Sign In button
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart
index 2816c775..42ea0442 100644
--- a/lib/services/api_service.dart
+++ b/lib/services/api_service.dart
@@ -229,6 +229,33 @@ class ApiService {
}
}
+ /// Validate an API key by hitting `/api/me`. Returns the user JSON and the
+ /// HTTP status code. API keys are sent as a Bearer token, same as JWT/legacy
+ /// tokens, so successful validation lets us reuse the legacy-token path
+ /// (no refresh, persists like any other session).
+ static Future<(Map<String, dynamic>?, int)> loginWithApiKey({
+ required String serverUrl,
+ required String apiKey,
+ Map<String, String> customHeaders = const {},
+ }) async {
+ final base = serverUrl.endsWith('/') ? serverUrl : '$serverUrl/';
+ final url = '${base}api/me';
+
+ try {
+ final response = await http.get(
+ Uri.parse(url),
+ headers: {...customHeaders, 'Authorization': 'Bearer $apiKey'},
+ ).timeout(const Duration(seconds: 15));
+
+ if (response.statusCode == 200) {
+ return (jsonDecode(response.body) as Map<String, dynamic>, 200);
+ }
+ return (null, response.statusCode);
+ } catch (_) {
+ return (null, 0);
+ }
+ }
+
/// Ping the server to check connectivity.
static Future<bool> pingServer(String serverUrl, {Map<String, String> customHeaders = const {}}) async {
final url = serverUrl.endsWith('/')