Enhance OIDC flow for better error handling and misconfiguration recovery

This commit is contained in:
aditya.chandel
2025-08-15 15:44:24 -06:00
committed by Aditya Chandel
parent 628a6c7bcf
commit 44541849ff
7 changed files with 225 additions and 42 deletions
@@ -17,7 +17,7 @@ public class PublicAppSettingController {
private final AppSettingService appSettingService;
@GetMapping
public List<PublicAppSetting> getPublicSettings() {
public PublicAppSetting getPublicSettings() {
return appSettingService.getPublicSettings();
}
}
@@ -21,9 +21,9 @@ public class AppSettings {
private Integer pdfCacheSizeInMb;
private Integer maxFileUploadSizeInMb;
private boolean remoteAuthEnabled;
private boolean oidcEnabled;
private boolean bookDeletionEnabled;
private boolean metadataDownloadOnBookdrop;
private boolean oidcEnabled;
private OidcProviderDetails oidcProviderDetails;
private OidcAutoProvisionDetails oidcAutoProvisionDetails;
private MetadataProviderSettings metadataProviderSettings;
@@ -1,11 +1,12 @@
package com.adityachandel.booklore.model.dto.settings;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.*;
@Getter
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class PublicAppSetting {
private final String key;
private final Object value;
private boolean oidcEnabled;
private OidcProviderDetails oidcProviderDetails;
}
@@ -9,8 +9,6 @@ import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
@@ -51,14 +49,8 @@ public class AppSettingService {
refreshCache();
}
public List<PublicAppSetting> getPublicSettings() {
return Arrays.stream(AppSettingKey.values())
.filter(AppSettingKey::isPublic)
.map(key -> new PublicAppSetting(
key.toString(),
settingPersistenceHelper.getOrCreateSetting(key, null)
))
.toList();
public PublicAppSetting getPublicSettings() {
return buildPublicSetting();
}
private void refreshCache() {
@@ -70,8 +62,22 @@ public class AppSettingService {
}
}
private Map<String, String> getSettingsMap() {
return settingPersistenceHelper.appSettingsRepository.findAll().stream().collect(Collectors.toMap(AppSettingEntity::getName, AppSettingEntity::getVal));
}
private PublicAppSetting buildPublicSetting() {
Map<String, String> settingsMap = getSettingsMap();
PublicAppSetting.PublicAppSettingBuilder builder = PublicAppSetting.builder();
builder.oidcEnabled(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.OIDC_ENABLED, "false")));
builder.oidcProviderDetails(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.OIDC_PROVIDER_DETAILS, OidcProviderDetails.class, null, false));
return builder.build();
}
private AppSettings buildAppSettings() {
Map<String, String> settingsMap = settingPersistenceHelper.appSettingsRepository.findAll().stream().collect(Collectors.toMap(AppSettingEntity::getName, AppSettingEntity::getVal));
Map<String, String> settingsMap = getSettingsMap();
AppSettings.AppSettingsBuilder builder = AppSettings.builder();
builder.remoteAuthEnabled(appProperties.getRemoteAuth().isEnabled());
+58 -4
View File
@@ -4,6 +4,20 @@ import {AuthService, websocketInitializer} from './core/service/auth.service';
import {AuthInitializationService} from './auth-initialization-service';
import {PublicAppSettingService} from './public-app-settings.service';
const OIDC_BYPASS_KEY = 'booklore-oidc-bypass';
const OIDC_ERROR_COUNT_KEY = 'booklore-oidc-error-count';
const MAX_OIDC_RETRIES = 3;
const OIDC_TIMEOUT_MS = 5000;
function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
return Promise.race([
promise,
new Promise<T>((_, reject) =>
setTimeout(() => reject(new Error(`Operation timed out after ${timeoutMs}ms`)), timeoutMs)
)
]);
}
export function initializeAuthFactory() {
return () => {
const oauthService = inject(OAuthService);
@@ -14,7 +28,10 @@ export function initializeAuthFactory() {
return new Promise<void>((resolve) => {
const sub = publicAppSettingService.publicAppSettings$.subscribe(publicSettings => {
if (publicSettings) {
if (publicSettings.oidcEnabled && publicSettings.oidcProviderDetails) {
const oidcBypassed = localStorage.getItem(OIDC_BYPASS_KEY) === 'true';
const errorCount = parseInt(localStorage.getItem(OIDC_ERROR_COUNT_KEY) || '0', 10);
if (publicSettings.oidcEnabled && publicSettings.oidcProviderDetails && !oidcBypassed && errorCount < MAX_OIDC_RETRIES) {
const details = publicSettings.oidcProviderDetails;
oauthService.configure({
@@ -28,9 +45,13 @@ export function initializeAuthFactory() {
strictDiscoveryDocumentValidation: false,
});
oauthService.loadDiscoveryDocumentAndTryLogin()
console.log(`[OIDC] Attempting discovery and login (attempt ${errorCount + 1}/${MAX_OIDC_RETRIES})`);
withTimeout(oauthService.loadDiscoveryDocumentAndTryLogin(), OIDC_TIMEOUT_MS)
.then(() => {
console.log('[OIDC] Discovery document loaded and login attempted');
localStorage.removeItem(OIDC_ERROR_COUNT_KEY);
if (oauthService.hasValidAccessToken()) {
authService.tokenSubject.next(oauthService.getAccessToken())
console.log('[OIDC] Valid access token found after tryLogin');
@@ -45,15 +66,35 @@ export function initializeAuthFactory() {
}
})
.catch(err => {
const newErrorCount = errorCount + 1;
localStorage.setItem(OIDC_ERROR_COUNT_KEY, newErrorCount.toString());
authInitService.markAsInitialized();
const isTimeout = err.message.includes('timed out');
const errorType = isTimeout ? 'timeout' : 'network/configuration';
console.error(
'OIDC initialization failed: Unable to complete OpenID Connect discovery or login. ' +
'This may be due to an incorrect issuer URL, client ID, or network issue. ' +
`OIDC initialization failed (${errorType}, attempt ${newErrorCount}/${MAX_OIDC_RETRIES}): ` +
'Unable to complete OpenID Connect discovery or login. ' +
`${isTimeout ? 'The request timed out after ' + OIDC_TIMEOUT_MS + 'ms. ' : ''}` +
'This may be due to an incorrect issuer URL, client ID, network issue, or slow server response. ' +
'Falling back to local login. Details:', err
);
if (newErrorCount >= MAX_OIDC_RETRIES) {
console.warn(`[OIDC] Maximum retry attempts (${MAX_OIDC_RETRIES}) exceeded. OIDC will be automatically bypassed until manually re-enabled.`);
localStorage.setItem(OIDC_BYPASS_KEY, 'true');
}
resolve();
});
} else {
if (oidcBypassed) {
console.log('[OIDC] OIDC is manually bypassed, using local authentication only');
} else if (errorCount >= MAX_OIDC_RETRIES) {
console.log(`[OIDC] OIDC automatically bypassed due to ${errorCount} consecutive errors`);
}
authInitService.markAsInitialized();
resolve();
}
@@ -63,3 +104,16 @@ export function initializeAuthFactory() {
});
};
}
export function resetOidcBypass(): void {
localStorage.removeItem(OIDC_BYPASS_KEY);
localStorage.removeItem(OIDC_ERROR_COUNT_KEY);
}
export function isOidcBypassed(): boolean {
return localStorage.getItem(OIDC_BYPASS_KEY) === 'true';
}
export function getOidcErrorCount(): number {
return parseInt(localStorage.getItem(OIDC_ERROR_COUNT_KEY) || '0', 10);
}
@@ -1,7 +1,7 @@
<div class="flex items-center justify-center min-h-screen min-w-[100vw] overflow-hidden"
style="background: linear-gradient(60deg, var(--primary-color) 0%, #1e3a8a 100%);">
<div class="flex flex-col items-center justify-center -mt-48">
<div style="border-radius: 56px; padding: 0.3rem; background: linear-gradient(180deg, var(--primary-color) 10%, rgba(33, 150, 243, 0) 30%)">
<div class="flex flex-col items-center justify-center -mt-48 w-[90%] sm:w-auto sm:min-w-[400px] md:min-w-[500px]">
<div class="w-full" style="border-radius: 56px; padding: 0.3rem; background: linear-gradient(180deg, var(--primary-color) 10%, rgba(33, 150, 243, 0) 30%)">
<div class="w-full bg-surface-900 pt-8 pb-12 px-8 sm:px-8" style="border-radius: 53px">
<div class="text-center mb-8">
<svg class="mb-8 w-14 h-14 mx-auto" viewBox="0 0 126 126" fill="var(--primary-color)" xmlns="http://www.w3.org/2000/svg">
@@ -15,17 +15,48 @@
<span class="font-medium">Sign in to continue</span>
</div>
<form class="flex flex-col gap-4" #loginForm="ngForm" (ngSubmit)="login()">
@if (showOidcBypassInfo) {
<div class="mb-4 p-3 rounded-md bg-yellow-900/30 border border-yellow-600/50 w-full">
<div class="flex flex-col items-center">
<div class="flex items-center gap-2 text-yellow-200 text-sm mb-2">
<i class="pi pi-exclamation-triangle"></i>
<span class="font-medium">OIDC Authentication Issues Detected</span>
</div>
<p class="text-xs text-yellow-300 mb-3 text-center">
{{ oidcBypassMessage }}
</p>
<div class="flex gap-4">
<p-button
size="small"
severity="warn"
label="Retry OIDC"
icon="pi pi-refresh"
(click)="retryOidc()"
/>
<p-button
size="small"
severity="success"
label="Use Local Login"
icon="pi pi-times"
(click)="dismissOidcWarning()"
/>
</div>
</div>
</div>
}
<form class="flex flex-col gap-4 w-full" #loginForm="ngForm" (ngSubmit)="login()">
<div class="flex flex-col gap-2">
<label for="username" class="text-lg font-medium">Username</label>
<input
fluid
pInputText
id="username"
name="username"
required
[(ngModel)]="username"
placeholder="Enter your username"
class="w-full md:w-[27rem]"
class="w-full"
/>
</div>
@@ -39,24 +70,25 @@
[feedback]="false"
placeholder="Enter your password"
[toggleMask]="true"
styleClass="mb-4"
class="mb-4"
[fluid]="true"
></p-password>
</div>
<p-button
fluid
type="submit"
label="Login"
icon="pi pi-sign-in"
[disabled]="!loginForm.valid || !username || !password"
styleClass="w-full"
></p-button>
class="w-full">
</p-button>
@if (errorMessage) {
<p-message severity="error" text="{{ errorMessage }}"></p-message>
<p-message severity="error">{{ errorMessage }}</p-message>
}
@if (oidcEnabled) {
@if (oidcEnabled && !isOidcBypassed) {
<div class="flex items-center gap-2 my-2">
<hr class="flex-grow" style="border: none; border-top: 1px solid var(--border-color);"/>
<span class="text-gray-300">or</span>
@@ -66,11 +98,31 @@
<p-button
fluid
severity="info"
label="Login with {{ oidcName }}"
icon="pi pi-id-card"
[label]="isOidcLoginInProgress ? 'Redirecting to ' + oidcName + '...' : 'Login with ' + oidcName"
[icon]="isOidcLoginInProgress ? 'pi pi-spin pi-spinner' : 'pi pi-id-card'"
[disabled]="isOidcLoginInProgress"
(click)="loginWithOidc()"
styleClass="w-full bg-gray-800 text-white hover:bg-gray-700"
/>
class="w-full bg-gray-800 text-white hover:bg-gray-700"/>
<div class="text-center">
<button
type="button"
class="text-xs text-gray-400 hover:text-gray-300 underline"
(click)="bypassOidc()">
Having trouble with {{ oidcName }}? Use local login only
</button>
</div>
}
@if (oidcEnabled && isOidcBypassed) {
<div class="text-center mt-4">
<button
type="button"
class="text-xs text-blue-400 hover:text-blue-300 underline"
(click)="enableOidc()">
Re-enable {{ oidcName }} login
</button>
</div>
}
</form>
</div>
@@ -1,4 +1,4 @@
import {Component, inject, OnInit} from '@angular/core';
import {Component, inject, OnInit, OnDestroy} from '@angular/core';
import {AuthService} from '../../service/auth.service';
import {Router} from '@angular/router';
import {FormsModule} from '@angular/forms';
@@ -7,11 +7,10 @@ import {Button} from 'primeng/button';
import {Message} from 'primeng/message';
import {InputText} from 'primeng/inputtext';
import {OAuthService} from 'angular-oauth2-oidc';
import {AppSettingsService} from '../../service/app-settings.service';
import {AppSettings} from '../../model/app-settings.model';
import {Observable} from 'rxjs';
import {filter, take} from 'rxjs/operators';
import {Observable, Subject} from 'rxjs';
import {filter, take, takeUntil} from 'rxjs/operators';
import {PublicAppSettings, PublicAppSettingService} from '../../../public-app-settings.service';
import {getOidcErrorCount, isOidcBypassed, resetOidcBypass} from '../../../auth-initializer';
@Component({
selector: 'app-login',
@@ -25,12 +24,16 @@ import {PublicAppSettings, PublicAppSettingService} from '../../../public-app-se
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
export class LoginComponent implements OnInit, OnDestroy {
username = '';
password = '';
errorMessage = '';
oidcEnabled = false;
oidcName = 'OIDC';
isOidcBypassed = false;
showOidcBypassInfo = false;
oidcBypassMessage = '';
isOidcLoginInProgress = false;
private authService = inject(AuthService);
private oAuthService = inject(OAuthService);
@@ -39,6 +42,8 @@ export class LoginComponent implements OnInit {
publicAppSettings$: Observable<PublicAppSettings | null> = this.appSettingsService.publicAppSettings$;
private destroy$ = new Subject<void>();
ngOnInit(): void {
this.publicAppSettings$
.pipe(
@@ -48,9 +53,27 @@ export class LoginComponent implements OnInit {
.subscribe(publicSettings => {
this.oidcEnabled = publicSettings!.oidcEnabled;
this.oidcName = publicSettings!.oidcProviderDetails?.providerName || 'OIDC';
this.checkOidcBypassStatus();
});
}
private checkOidcBypassStatus(): void {
this.isOidcBypassed = isOidcBypassed();
const errorCount = getOidcErrorCount();
if (this.oidcEnabled && (this.isOidcBypassed || errorCount > 0)) {
this.showOidcBypassInfo = true;
if (this.isOidcBypassed && errorCount >= 3) {
this.oidcBypassMessage = `${this.oidcName} authentication has been automatically disabled after ${errorCount} consecutive failures (including timeouts). You can retry or continue with local login.`;
} else if (this.isOidcBypassed) {
this.oidcBypassMessage = `${this.oidcName} authentication has been manually disabled. You can re-enable it or continue with local login.`;
} else if (errorCount > 0) {
this.oidcBypassMessage = `${this.oidcName} authentication encountered ${errorCount} error(s), possibly due to timeouts or server issues.`;
}
}
}
login(): void {
this.authService.internalLogin({username: this.username, password: this.password}).subscribe({
next: (response) => {
@@ -71,6 +94,53 @@ export class LoginComponent implements OnInit {
}
loginWithOidc(): void {
this.oAuthService.initCodeFlow();
if (this.isOidcLoginInProgress) {
return;
}
this.isOidcLoginInProgress = true;
this.errorMessage = '';
try {
setTimeout(() => {
this.isOidcLoginInProgress = false;
}, 5000);
this.oAuthService.initCodeFlow();
} catch (error) {
console.error('OIDC login initiation failed:', error);
this.errorMessage = 'Failed to initiate OIDC login. Please try again or use local login.';
this.isOidcLoginInProgress = false;
}
}
bypassOidc(): void {
localStorage.setItem('booklore-oidc-bypass', 'true');
this.isOidcBypassed = true;
this.showOidcBypassInfo = false;
}
enableOidc(): void {
resetOidcBypass();
this.isOidcBypassed = false;
this.showOidcBypassInfo = false;
this.isOidcLoginInProgress = false;
window.location.reload();
}
retryOidc(): void {
resetOidcBypass();
this.isOidcBypassed = false;
this.showOidcBypassInfo = false;
this.isOidcLoginInProgress = false;
window.location.reload();
}
dismissOidcWarning(): void {
this.showOidcBypassInfo = false;
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
}