Resolve broken Pocket ID auth and occasional Authentik failures
This commit is contained in:
committed by
Aditya Chandel
parent
98bd69164b
commit
f7db157689
+28
-48
@@ -10,18 +10,7 @@ import com.adityachandel.booklore.model.entity.UserPermissionsEntity;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.service.user.UserProvisioningService;
|
||||
import com.nimbusds.jose.JWSAlgorithm;
|
||||
import com.nimbusds.jose.jwk.source.DefaultJWKSetCache;
|
||||
import com.nimbusds.jose.jwk.source.JWKSetCache;
|
||||
import com.nimbusds.jose.jwk.source.JWKSource;
|
||||
import com.nimbusds.jose.jwk.source.RemoteJWKSet;
|
||||
import com.nimbusds.jose.proc.JWSKeySelector;
|
||||
import com.nimbusds.jose.proc.JWSVerificationKeySelector;
|
||||
import com.nimbusds.jose.proc.SecurityContext;
|
||||
import com.nimbusds.jose.util.DefaultResourceRetriever;
|
||||
import com.nimbusds.jwt.JWTClaimsSet;
|
||||
import com.nimbusds.jwt.proc.ConfigurableJWTProcessor;
|
||||
import com.nimbusds.jwt.proc.DefaultJWTProcessor;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
@@ -37,14 +26,11 @@ import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.URL;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@@ -56,6 +42,9 @@ public class DualJwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
private final UserRepository userRepository;
|
||||
private final AppSettingService appSettingService;
|
||||
private final UserProvisioningService userProvisioningService;
|
||||
private static final ConcurrentMap<String, Object> userLocks = new ConcurrentHashMap<>();
|
||||
private final DynamicOidcJwtProcessor dynamicOidcJwtProcessor;
|
||||
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
|
||||
@@ -103,50 +92,41 @@ public class DualJwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
private void authenticateOidcUser(String token, HttpServletRequest request) {
|
||||
try {
|
||||
OidcProviderDetails providerDetails = appSettingService.getAppSettings().getOidcProviderDetails();
|
||||
String jwksUrl = providerDetails.getJwksUrl();
|
||||
if (jwksUrl == null || jwksUrl.isEmpty()) {
|
||||
log.error("JWKS URL is not configured.");
|
||||
throw ApiError.UNAUTHORIZED.createException("JWKS URL is not configured.");
|
||||
}
|
||||
JWTClaimsSet claimsSet = dynamicOidcJwtProcessor.getProcessor().process(token, null);
|
||||
|
||||
List<String> defaultOidcUserPermissions = appSettingService.getAppSettings().getOidcAutoProvisionDetails().getDefaultPermissions();
|
||||
OidcProviderDetails.ClaimMapping claimMapping = providerDetails.getClaimMapping();
|
||||
URL jwksURL = new URI(jwksUrl).toURL();
|
||||
|
||||
DefaultResourceRetriever resourceRetriever = new DefaultResourceRetriever(2000, 2000);
|
||||
Duration ttl = Duration.ofHours(6);
|
||||
Duration refresh = Duration.ofHours(1);
|
||||
JWKSetCache jwkSetCache = new DefaultJWKSetCache(ttl.toMillis(), refresh.toMillis(), TimeUnit.MILLISECONDS);
|
||||
JWKSource<SecurityContext> jwkSource = new RemoteJWKSet<>(jwksURL, resourceRetriever, jwkSetCache);
|
||||
|
||||
ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
|
||||
JWSKeySelector<SecurityContext> keySelector = new JWSVerificationKeySelector<>(JWSAlgorithm.RS256, jwkSource);
|
||||
jwtProcessor.setJWSKeySelector(keySelector);
|
||||
|
||||
JWTClaimsSet claimsSet = jwtProcessor.process(token, null);
|
||||
Date expirationTime = claimsSet.getExpirationTime();
|
||||
if (expirationTime == null || expirationTime.before(new Date())) {
|
||||
log.warn("OIDC token is expired or missing exp claim");
|
||||
throw ApiError.UNAUTHORIZED.createException("Token has expired or is invalid.");
|
||||
}
|
||||
|
||||
OidcProviderDetails.ClaimMapping claimMapping = providerDetails.getClaimMapping();
|
||||
String username = claimsSet.getStringClaim(claimMapping.getUsername());
|
||||
String email = claimsSet.getStringClaim(claimMapping.getEmail());
|
||||
String name = claimsSet.getStringClaim(claimMapping.getName());
|
||||
|
||||
boolean autoProvisionOidcUsers = appSettingService.getAppSettings().getOidcAutoProvisionDetails().isEnableAutoProvisioning();
|
||||
OidcAutoProvisionDetails oidcAutoProvisionDetails = appSettingService.getAppSettings().getOidcAutoProvisionDetails();
|
||||
OidcAutoProvisionDetails provisionDetails = appSettingService.getAppSettings().getOidcAutoProvisionDetails();
|
||||
boolean autoProvision = provisionDetails != null && provisionDetails.isEnableAutoProvisioning();
|
||||
|
||||
Optional<BookLoreUserEntity> userOpt = userRepository.findByUsername(username);
|
||||
if (userOpt.isEmpty()) {
|
||||
if (!autoProvisionOidcUsers) {
|
||||
log.warn("User '{}' not found and auto-provisioning is disabled", username);
|
||||
throw ApiError.UNAUTHORIZED.createException("User not found and auto-provisioning is disabled.");
|
||||
}
|
||||
log.info("Provisioning new OIDC user '{}'", username);
|
||||
}
|
||||
|
||||
BookLoreUserEntity entity = userOpt.orElseGet(() -> userProvisioningService.provisionOidcUser(username, email, name, oidcAutoProvisionDetails));
|
||||
BookLoreUserEntity entity = userRepository.findByUsername(username)
|
||||
.orElseGet(() -> {
|
||||
if (!autoProvision) {
|
||||
log.warn("User '{}' not found and auto-provisioning is disabled.", username);
|
||||
throw ApiError.UNAUTHORIZED.createException("User not found and auto-provisioning is disabled.");
|
||||
}
|
||||
Object lock = userLocks.computeIfAbsent(username, k -> new Object());
|
||||
try {
|
||||
synchronized (lock) {
|
||||
return userRepository.findByUsername(username)
|
||||
.orElseGet(() -> {
|
||||
log.info("Provisioning new OIDC user '{}'", username);
|
||||
return userProvisioningService.provisionOidcUser(username, email, name, provisionDetails);
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
userLocks.remove(username);
|
||||
}
|
||||
});
|
||||
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
List<GrantedAuthority> authorities = getAuthorities(entity.getPermissions());
|
||||
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.settings.OidcProviderDetails;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.nimbusds.jose.JWSAlgorithm;
|
||||
import com.nimbusds.jose.jwk.source.DefaultJWKSetCache;
|
||||
import com.nimbusds.jose.jwk.source.JWKSetCache;
|
||||
import com.nimbusds.jose.jwk.source.JWKSource;
|
||||
import com.nimbusds.jose.jwk.source.RemoteJWKSet;
|
||||
import com.nimbusds.jose.proc.JWSKeySelector;
|
||||
import com.nimbusds.jose.proc.JWSVerificationKeySelector;
|
||||
import com.nimbusds.jose.proc.SecurityContext;
|
||||
import com.nimbusds.jose.util.DefaultResourceRetriever;
|
||||
import com.nimbusds.jwt.proc.ConfigurableJWTProcessor;
|
||||
import com.nimbusds.jwt.proc.DefaultJWTProcessor;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.net.URL;
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class DynamicOidcJwtProcessor {
|
||||
private final AppSettingService appSettingService;
|
||||
|
||||
private volatile ConfigurableJWTProcessor<SecurityContext> jwtProcessor;
|
||||
private volatile String currentIssuerUri;
|
||||
|
||||
public synchronized ConfigurableJWTProcessor<SecurityContext> getProcessor() throws Exception {
|
||||
String issuerUri = appSettingService.getAppSettings().getOidcProviderDetails().getIssuerUri();
|
||||
if (jwtProcessor == null || !issuerUri.equals(currentIssuerUri)) {
|
||||
this.jwtProcessor = buildProcessor(issuerUri);
|
||||
this.currentIssuerUri = issuerUri;
|
||||
}
|
||||
return jwtProcessor;
|
||||
}
|
||||
|
||||
private ConfigurableJWTProcessor<SecurityContext> buildProcessor(String issuerUri) throws Exception {
|
||||
OidcProviderDetails providerDetails = appSettingService.getAppSettings().getOidcProviderDetails();
|
||||
|
||||
if (providerDetails == null || providerDetails.getIssuerUri() == null || providerDetails.getIssuerUri().isEmpty()) {
|
||||
throw new IllegalStateException("OIDC issuer URI is not configured in app settings.");
|
||||
}
|
||||
|
||||
String discoveryUri = providerDetails.getIssuerUri() + "/.well-known/openid-configuration";
|
||||
log.info("Fetching OIDC discovery document from {}", discoveryUri);
|
||||
|
||||
URL jwksUrl = fetchJwksUri(discoveryUri);
|
||||
|
||||
DefaultResourceRetriever resourceRetriever = new DefaultResourceRetriever(2000, 2000);
|
||||
|
||||
Duration ttl = Duration.ofHours(6);
|
||||
Duration refresh = Duration.ofHours(1);
|
||||
JWKSetCache jwkSetCache = new DefaultJWKSetCache(ttl.toMillis(), refresh.toMillis(), TimeUnit.MILLISECONDS);
|
||||
|
||||
JWKSource<SecurityContext> jwkSource = new RemoteJWKSet<>(jwksUrl, resourceRetriever, jwkSetCache);
|
||||
|
||||
JWSKeySelector<SecurityContext> keySelector = new JWSVerificationKeySelector<>(JWSAlgorithm.RS256, jwkSource);
|
||||
ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
|
||||
jwtProcessor.setJWSKeySelector(keySelector);
|
||||
|
||||
return jwtProcessor;
|
||||
}
|
||||
|
||||
private URL fetchJwksUri(String discoveryUri) throws Exception {
|
||||
var restClient = org.springframework.web.client.RestClient.create();
|
||||
var discoveryDoc = restClient.get()
|
||||
.uri(discoveryUri)
|
||||
.retrieve()
|
||||
.body(new org.springframework.core.ParameterizedTypeReference<java.util.Map<String, Object>>() {});
|
||||
|
||||
String jwksUri = (String) discoveryDoc.get("jwks_uri");
|
||||
if (jwksUri == null || jwksUri.isEmpty()) {
|
||||
throw new IllegalStateException("jwks_uri not found in OIDC discovery document.");
|
||||
}
|
||||
return new URL(jwksUri);
|
||||
}
|
||||
}
|
||||
-64
@@ -1,64 +0,0 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.settings.OidcProviderDetails;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.nimbusds.jose.JWSAlgorithm;
|
||||
import com.nimbusds.jose.jwk.source.JWKSource;
|
||||
import com.nimbusds.jose.jwk.source.RemoteJWKSet;
|
||||
import com.nimbusds.jose.proc.JWSKeySelector;
|
||||
import com.nimbusds.jose.proc.JWSVerificationKeySelector;
|
||||
import com.nimbusds.jose.proc.SecurityContext;
|
||||
import com.nimbusds.jose.util.DefaultResourceRetriever;
|
||||
import com.nimbusds.jwt.JWTClaimsSet;
|
||||
import com.nimbusds.jwt.proc.ConfigurableJWTProcessor;
|
||||
import com.nimbusds.jwt.proc.DefaultJWTProcessor;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URL;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class OidcTokenValidator {
|
||||
|
||||
private final AppSettingService appSettingService;
|
||||
|
||||
public Authentication validate(String token) {
|
||||
if (!appSettingService.getAppSettings().isOidcEnabled()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
OidcProviderDetails providerDetails = appSettingService.getAppSettings().getOidcProviderDetails();
|
||||
String jwksUrl = providerDetails.getJwksUrl();
|
||||
if (jwksUrl == null || jwksUrl.isEmpty()) {
|
||||
log.error("JWKS URL is not configured");
|
||||
return null;
|
||||
}
|
||||
|
||||
URL jwksURL = new URI(jwksUrl).toURL();
|
||||
DefaultResourceRetriever resourceRetriever = new DefaultResourceRetriever(2000, 2000);
|
||||
JWKSource<SecurityContext> jwkSource = new RemoteJWKSet<>(jwksURL, resourceRetriever);
|
||||
ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
|
||||
JWSKeySelector<SecurityContext> keySelector = new JWSVerificationKeySelector<>(JWSAlgorithm.RS256, jwkSource);
|
||||
jwtProcessor.setJWSKeySelector(keySelector);
|
||||
|
||||
JWTClaimsSet claimsSet = jwtProcessor.process(token, null);
|
||||
Date expirationTime = claimsSet.getExpirationTime();
|
||||
if (expirationTime == null || expirationTime.before(new Date())) {
|
||||
log.warn("OIDC token is expired or missing exp claim");
|
||||
return null;
|
||||
}
|
||||
return new UsernamePasswordAuthenticationToken("oidc-user", null, Collections.emptyList());
|
||||
} catch (Exception e) {
|
||||
log.error("OIDC token validation failed", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+15
-10
@@ -1,5 +1,6 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
|
||||
import com.nimbusds.jwt.JWTClaimsSet;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.Ordered;
|
||||
@@ -25,7 +26,7 @@ import java.util.List;
|
||||
public class WebSocketAuthInterceptor implements ChannelInterceptor {
|
||||
|
||||
private final JwtUtils jwtUtils;
|
||||
private final OidcTokenValidator oidcTokenValidator;
|
||||
private final DynamicOidcJwtProcessor dynamicOidcJwtProcessor;
|
||||
|
||||
@Override
|
||||
public Message<?> preSend(Message<?> message, MessageChannel channel) {
|
||||
@@ -55,15 +56,19 @@ public class WebSocketAuthInterceptor implements ChannelInterceptor {
|
||||
}
|
||||
|
||||
private Authentication authenticateToken(String token) {
|
||||
if (jwtUtils.validateToken(token)) {
|
||||
String username = jwtUtils.extractUsername(token);
|
||||
return new UsernamePasswordAuthenticationToken(
|
||||
username,
|
||||
null,
|
||||
Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
|
||||
);
|
||||
try {
|
||||
if (jwtUtils.validateToken(token)) {
|
||||
String username = jwtUtils.extractUsername(token);
|
||||
return new UsernamePasswordAuthenticationToken(username, null, Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")));
|
||||
}
|
||||
JWTClaimsSet claims = dynamicOidcJwtProcessor.getProcessor().process(token, null);
|
||||
if (claims != null) {
|
||||
String username = claims.getSubject();
|
||||
return new UsernamePasswordAuthenticationToken(username, null, Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Token authentication failed", e);
|
||||
}
|
||||
|
||||
return oidcTokenValidator.validate(token);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+10
-1
@@ -11,6 +11,7 @@ import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@@ -72,7 +73,15 @@ public class BookLoreUserTransformer {
|
||||
}
|
||||
|
||||
bookLoreUser.setUserSettings(userSettings);
|
||||
bookLoreUser.setAssignedLibraries(userEntity.getLibraries().stream().map(libraryMapper::toLibrary).collect(Collectors.toList()));
|
||||
if (userEntity.getLibraries() != null) {
|
||||
bookLoreUser.setAssignedLibraries(
|
||||
userEntity.getLibraries().stream()
|
||||
.map(libraryMapper::toLibrary)
|
||||
.collect(Collectors.toList())
|
||||
);
|
||||
} else {
|
||||
bookLoreUser.setAssignedLibraries(Collections.emptyList());
|
||||
}
|
||||
bookLoreUser.setProvisioningMethod(userEntity.getProvisioningMethod());
|
||||
return bookLoreUser;
|
||||
}
|
||||
|
||||
-1
@@ -7,7 +7,6 @@ public class OidcProviderDetails {
|
||||
private String providerName;
|
||||
private String clientId;
|
||||
private String issuerUri;
|
||||
private String jwksUrl;
|
||||
private ClaimMapping claimMapping;
|
||||
|
||||
@Data
|
||||
|
||||
+1
-2
@@ -44,8 +44,7 @@ public class DefaultSettingInitializer {
|
||||
}
|
||||
|
||||
private void addSettingIfMissing(BookLoreUserEntity user, UserSettingKey key, Object value) {
|
||||
boolean exists = user.getSettings().stream()
|
||||
.anyMatch(s -> s.getSettingKey().equals(key.getDbKey()));
|
||||
boolean exists = user.getSettings().stream().anyMatch(s -> s.getSettingKey().equals(key.getDbKey()));
|
||||
if (!exists) {
|
||||
try {
|
||||
String serializedValue = key.isJson()
|
||||
|
||||
+5
-2
@@ -37,11 +37,14 @@ public class UserDefaultsService {
|
||||
|
||||
private void add(BookLoreUserEntity user, UserSettingKey key, Object value) {
|
||||
try {
|
||||
String json = objectMapper.writeValueAsString(value);
|
||||
String storedValue = key.isJson()
|
||||
? objectMapper.writeValueAsString(value)
|
||||
: value.toString();
|
||||
|
||||
user.getSettings().add(UserSettingEntity.builder()
|
||||
.user(user)
|
||||
.settingKey(key.getDbKey())
|
||||
.settingValue(json)
|
||||
.settingValue(storedValue)
|
||||
.build());
|
||||
} catch (Exception e) {
|
||||
log.error("Error serializing setting {} for user {}", key, user.getUsername(), e);
|
||||
|
||||
@@ -1,3 +1,14 @@
|
||||
<p-confirmDialog />
|
||||
<p-toast></p-toast>
|
||||
<router-outlet></router-outlet>
|
||||
@if (loading) {
|
||||
<div class="splash-screen">
|
||||
<div class="splash-content">
|
||||
<img src="assets/favicon.svg" alt="Booklore logo" class="logo" />
|
||||
<h1>Loading Booklore…</h1>
|
||||
<p>Please wait while we get things ready.</p>
|
||||
<div class="loader"></div>
|
||||
</div>
|
||||
</div>
|
||||
} @else {
|
||||
<p-confirmDialog />
|
||||
<p-toast></p-toast>
|
||||
<router-outlet></router-outlet>
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
.splash-screen {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100dvh;
|
||||
background-color: #0e0e10;
|
||||
color: #e5e5e5;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.splash-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 1.5rem;
|
||||
}
|
||||
|
||||
.logo {
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 1.8rem;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
p {
|
||||
font-size: 1rem;
|
||||
color: #a0a0a0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.loader {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border: 4px solid #818cf8;
|
||||
border-top: 4px solid transparent;
|
||||
border-radius: 50%;
|
||||
animation: spin 1s linear infinite;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import {parseLogNotification} from './shared/websocket/model/log-notification.mo
|
||||
import {ConfirmDialog} from 'primeng/confirmdialog';
|
||||
import {Toast} from 'primeng/toast';
|
||||
import {RouterOutlet} from '@angular/router';
|
||||
import {AuthInitializationService} from './auth-initialization-service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
@@ -17,12 +18,18 @@ import {RouterOutlet} from '@angular/router';
|
||||
})
|
||||
export class AppComponent implements OnInit {
|
||||
|
||||
loading = true;
|
||||
private authInit = inject(AuthInitializationService);
|
||||
private bookService = inject(BookService);
|
||||
private rxStompService = inject(RxStompService);
|
||||
private eventService = inject(EventService);
|
||||
|
||||
ngOnInit(): void {
|
||||
|
||||
this.authInit.initialized$.subscribe(ready => {
|
||||
this.loading = !ready;
|
||||
});
|
||||
|
||||
this.rxStompService.watch('/topic/book-add').subscribe((message: Message) => {
|
||||
this.bookService.handleNewlyCreatedBook(JSON.parse(message.body));
|
||||
});
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
import {BehaviorSubject} from 'rxjs';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class AuthInitializationService {
|
||||
private initialized = new BehaviorSubject<boolean>(false);
|
||||
initialized$ = this.initialized.asObservable();
|
||||
|
||||
markAsInitialized() {
|
||||
this.initialized.next(true);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import {OAuthEvent, OAuthService} from 'angular-oauth2-oidc';
|
||||
import {AppSettingsService} from './core/service/app-settings.service';
|
||||
import {AuthService, websocketInitializer} from './core/service/auth.service';
|
||||
import {filter} from 'rxjs/operators';
|
||||
import {AuthInitializationService} from './auth-initialization-service';
|
||||
|
||||
export function initializeAuthFactory() {
|
||||
return () => {
|
||||
@@ -11,12 +12,14 @@ export function initializeAuthFactory() {
|
||||
const appSettingsService = inject(AppSettingsService);
|
||||
const authService = inject(AuthService);
|
||||
const router = inject(Router);
|
||||
const authInitService = inject(AuthInitializationService);
|
||||
|
||||
return new Promise<void>((resolve) => {
|
||||
const sub = appSettingsService.appSettings$.subscribe(settings => {
|
||||
if (settings) {
|
||||
if (settings.oidcEnabled && settings.oidcProviderDetails) {
|
||||
const details = settings.oidcProviderDetails;
|
||||
|
||||
oauthService.configure({
|
||||
issuer: details.issuerUri,
|
||||
clientId: details.clientId,
|
||||
@@ -24,27 +27,28 @@ export function initializeAuthFactory() {
|
||||
redirectUri: window.location.origin + '/oauth2-callback',
|
||||
responseType: 'code',
|
||||
showDebugInformation: false,
|
||||
requireHttps: true,
|
||||
requireHttps: false,
|
||||
strictDiscoveryDocumentValidation: false,
|
||||
});
|
||||
|
||||
oauthService.events
|
||||
.pipe(filter((e: OAuthEvent) =>
|
||||
e.type === 'token_received' || e.type === 'token_refreshed'
|
||||
))
|
||||
.subscribe((e: OAuthEvent) => {
|
||||
const accessToken = oauthService.getAccessToken();
|
||||
const refreshToken = oauthService.getRefreshToken();
|
||||
authService.saveOidcTokens(accessToken, refreshToken ?? '');
|
||||
});
|
||||
|
||||
oauthService.loadDiscoveryDocumentAndTryLogin()
|
||||
.then(() => {
|
||||
oauthService.setupAutomaticSilentRefresh();
|
||||
websocketInitializer(authService);
|
||||
resolve();
|
||||
console.log('[OIDC] Discovery document loaded and login attempted');
|
||||
if (oauthService.hasValidAccessToken()) {
|
||||
console.log('[OIDC] Valid access token found after tryLogin');
|
||||
router.navigate(['/dashboard']);
|
||||
oauthService.setupAutomaticSilentRefresh();
|
||||
websocketInitializer(authService);
|
||||
authInitService.markAsInitialized();
|
||||
resolve();
|
||||
} else {
|
||||
console.log('[OIDC] No valid access token found, attempting silent login with prompt=none');
|
||||
oauthService.initCodeFlow();
|
||||
resolve();
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
authInitService.markAsInitialized();
|
||||
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. ' +
|
||||
@@ -60,6 +64,7 @@ export function initializeAuthFactory() {
|
||||
error: resolve
|
||||
});
|
||||
} else {
|
||||
authInitService.markAsInitialized();
|
||||
resolve();
|
||||
}
|
||||
sub.unsubscribe();
|
||||
|
||||
@@ -1,32 +1,32 @@
|
||||
import { inject } from '@angular/core';
|
||||
import { CanActivateFn } from '@angular/router';
|
||||
import { Router } from '@angular/router';
|
||||
import { OAuthService } from 'angular-oauth2-oidc';
|
||||
import {AuthService} from './core/service/auth.service';
|
||||
import {OAuthService} from 'angular-oauth2-oidc';
|
||||
|
||||
export const AuthGuard: CanActivateFn = (route, state) => {
|
||||
const router = inject(Router);
|
||||
const authService = inject(AuthService);
|
||||
const oauthService = inject(OAuthService);
|
||||
|
||||
const legacyToken = localStorage.getItem('accessToken_Internal');
|
||||
const internalAccessToken = authService.getInternalAccessToken();
|
||||
|
||||
if (legacyToken) {
|
||||
if (internalAccessToken) {
|
||||
try {
|
||||
const payload = JSON.parse(atob(legacyToken.split('.')[1]));
|
||||
const payload = JSON.parse(atob(internalAccessToken.split('.')[1]));
|
||||
if (payload.isDefaultPassword) {
|
||||
router.navigate(['/change-password']);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (e) {
|
||||
console.error('Invalid legacy token:', e);
|
||||
localStorage.removeItem('accessToken');
|
||||
localStorage.removeItem('accessToken_Internal');
|
||||
router.navigate(['/login']);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const oidcToken = localStorage.getItem('accessToken_OIDC');
|
||||
|
||||
if (oidcToken) {
|
||||
if (oauthService.hasValidAccessToken()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -77,6 +77,6 @@ export class LoginComponent implements OnInit {
|
||||
}
|
||||
|
||||
loginWithOidc(): void {
|
||||
this.oAuthService.initImplicitFlow();
|
||||
this.oAuthService.initCodeFlow();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,7 +28,6 @@ export interface OidcProviderDetails {
|
||||
providerName: string;
|
||||
clientId: string;
|
||||
issuerUri: string;
|
||||
jwksUrl: string;
|
||||
claimMapping: {
|
||||
username: string;
|
||||
email: string;
|
||||
|
||||
+3
-12
@@ -79,16 +79,7 @@
|
||||
pInputText
|
||||
id="issuerUri"
|
||||
[(ngModel)]="oidcProvider.issuerUri"
|
||||
placeholder="e.g. https://authentik.your-domain.com/application/o/booklore/"
|
||||
class="w-full"/>
|
||||
</div>
|
||||
<div class="md:col-span-2">
|
||||
<label for="jwksUrl" class="mb-1">JWKS URL</label>
|
||||
<input
|
||||
pInputText
|
||||
id="jwksUrl"
|
||||
[(ngModel)]="oidcProvider.jwksUrl"
|
||||
placeholder="e.g. https://authentik.your-domain.com/application/o/booklore/jwks/"
|
||||
placeholder="e.g. https://authentik.domain.com/application/o/booklore/ or https://pocket-id.domain.com"
|
||||
class="w-full"/>
|
||||
</div>
|
||||
<div class="md:col-span-2">
|
||||
@@ -150,7 +141,7 @@
|
||||
<p-toggleswitch
|
||||
[(ngModel)]="autoUserProvisioningEnabled"
|
||||
inputId="autoProvision"
|
||||
(onChange)="saveAutoProvision()">
|
||||
(onChange)="saveOidcAutoProvisionSettings()">
|
||||
</p-toggleswitch>
|
||||
<div class="flex items-center gap-2 text-sm text-gray-400">
|
||||
<i class="pi pi-info-circle text-blue-500"></i>
|
||||
@@ -193,7 +184,7 @@
|
||||
</p-multiSelect>
|
||||
</div>
|
||||
<div class="mt-8">
|
||||
<p-button label="Save Settings" [outlined]="true" (click)="saveAutoProvisioningSettings()"></p-button>
|
||||
<p-button label="Save Settings" [outlined]="true" (click)="saveOidcAutoProvisionSettings()"></p-button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
+2
-50
@@ -30,7 +30,7 @@ import {LibraryService} from '../../../book/service/library.service';
|
||||
Button,
|
||||
MultiSelect,
|
||||
ReactiveFormsModule
|
||||
],
|
||||
],
|
||||
styleUrls: ['./authentication-settings.component.scss']
|
||||
})
|
||||
export class AuthenticationSettingsComponent implements OnInit {
|
||||
@@ -52,7 +52,6 @@ export class AuthenticationSettingsComponent implements OnInit {
|
||||
providerName: '',
|
||||
clientId: '',
|
||||
issuerUri: '',
|
||||
jwksUrl: '',
|
||||
claimMapping: {
|
||||
username: '',
|
||||
email: '',
|
||||
@@ -98,7 +97,6 @@ export class AuthenticationSettingsComponent implements OnInit {
|
||||
providerName: settings.oidcProviderDetails?.providerName || '',
|
||||
clientId: settings.oidcProviderDetails?.clientId || '',
|
||||
issuerUri: settings.oidcProviderDetails?.issuerUri || '',
|
||||
jwksUrl: settings.oidcProviderDetails?.jwksUrl || '',
|
||||
claimMapping: settings.oidcProviderDetails?.claimMapping || defaultClaimMapping
|
||||
};
|
||||
|
||||
@@ -112,51 +110,6 @@ export class AuthenticationSettingsComponent implements OnInit {
|
||||
return !!(p.providerName && p.clientId && p.issuerUri && p.claimMapping.name && p.claimMapping.email && p.claimMapping.username);
|
||||
}
|
||||
|
||||
saveAutoProvision(): void {
|
||||
const payload = [
|
||||
{key: 'auto_provision_oidc_users', newValue: this.autoUserProvisioningEnabled}
|
||||
];
|
||||
this.appSettingsService.saveSettings(payload).subscribe({
|
||||
next: () => this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Saved',
|
||||
detail: 'Auto-provision setting saved.'
|
||||
}),
|
||||
error: () => this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: 'Failed to save auto-provision setting.'
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
onPermissionToggle(): void {
|
||||
this.selectedPermissions = [
|
||||
'permissionRead',
|
||||
...this.availablePermissions.filter(p => p.selected).map(p => p.value)
|
||||
];
|
||||
|
||||
const payload = [
|
||||
{
|
||||
key: 'default_oidc_user_permissions',
|
||||
newValue: this.selectedPermissions
|
||||
}
|
||||
];
|
||||
|
||||
this.appSettingsService.saveSettings(payload).subscribe({
|
||||
next: () => this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Saved',
|
||||
detail: 'Default permissions updated.'
|
||||
}),
|
||||
error: () => this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: 'Failed to update default permissions.'
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
toggleOidcEnabled(): void {
|
||||
if (!this.isOidcFormComplete()) return;
|
||||
const payload = [
|
||||
@@ -200,8 +153,7 @@ export class AuthenticationSettingsComponent implements OnInit {
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
saveAutoProvisioningSettings(): void {
|
||||
saveOidcAutoProvisionSettings(): void {
|
||||
const provisionDetails = {
|
||||
enableAutoProvisioning: this.autoUserProvisioningEnabled,
|
||||
defaultPermissions: [
|
||||
|
||||
@@ -15,21 +15,22 @@ export class OidcCallbackComponent implements OnInit {
|
||||
private authService = inject(AuthService);
|
||||
|
||||
ngOnInit(): void {
|
||||
this.oAuthService.loadDiscoveryDocumentAndTryLogin().then(() => {
|
||||
/*this.oAuthService.tryLoginCodeFlow().then(info => {
|
||||
if (this.oAuthService.hasValidAccessToken()) {
|
||||
this.authService.saveOidcTokens(
|
||||
this.oAuthService.getAccessToken(),
|
||||
this.oAuthService.getRefreshToken()
|
||||
);
|
||||
const accessToken = this.oAuthService.getAccessToken();
|
||||
const refreshToken = this.oAuthService.getRefreshToken();
|
||||
this.authService.saveOidcTokens(accessToken, refreshToken ?? '');
|
||||
|
||||
this.authService.getRxStompService().activate();
|
||||
this.oAuthService.setupAutomaticSilentRefresh();
|
||||
this.router.navigate(['/dashboard']);
|
||||
} else {
|
||||
console.error('Login failed or no valid tokens');
|
||||
console.error('OIDC code exchange failed');
|
||||
this.router.navigate(['/login']);
|
||||
}
|
||||
}).catch(err => {
|
||||
console.error('OIDC error during login:', err);
|
||||
console.error('OIDC error:', err);
|
||||
this.router.navigate(['/login']);
|
||||
});
|
||||
});*/
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ export class AppConfigService {
|
||||
return {
|
||||
preset: 'Aura',
|
||||
primary: 'green',
|
||||
surface: 'viva',
|
||||
surface: 'neutral',
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,9 @@ import {Observable, tap} from 'rxjs';
|
||||
import {RxStompService} from '../../shared/websocket/rx-stomp.service';
|
||||
import {API_CONFIG} from '../../config/api-config';
|
||||
import {createRxStompConfig} from '../../shared/websocket/rx-stomp.config';
|
||||
import {OAuthService} from 'angular-oauth2-oidc';
|
||||
import {AppSettingsService} from './app-settings.service';
|
||||
import {Router} from '@angular/router';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
@@ -15,6 +18,8 @@ export class AuthService {
|
||||
|
||||
private http = inject(HttpClient);
|
||||
private injector = inject(Injector);
|
||||
private oAuthService = inject(OAuthService);
|
||||
private router = inject(Router);
|
||||
|
||||
internalLogin(credentials: { username: string; password: string }): Observable<{ accessToken: string; refreshToken: string, isDefaultPassword: string }> {
|
||||
return this.http.post<{ accessToken: string; refreshToken: string, isDefaultPassword: string }>(`${this.apiUrl}/login`, credentials).pipe(
|
||||
@@ -54,17 +59,12 @@ export class AuthService {
|
||||
localStorage.setItem('refreshToken_Internal', refreshToken);
|
||||
}
|
||||
|
||||
saveOidcTokens(accessToken: string, refreshToken: string): void {
|
||||
localStorage.setItem('accessToken_OIDC', accessToken);
|
||||
localStorage.setItem('refreshToken_OIDC', refreshToken);
|
||||
}
|
||||
|
||||
getInternalAccessToken(): string | null {
|
||||
return localStorage.getItem('accessToken_Internal');
|
||||
}
|
||||
|
||||
getOidcAccessToken(): string | null {
|
||||
return localStorage.getItem('accessToken_OIDC');
|
||||
return this.oAuthService.getIdToken();
|
||||
}
|
||||
|
||||
getInternalRefreshToken(): string | null {
|
||||
@@ -74,9 +74,12 @@ export class AuthService {
|
||||
logout(): void {
|
||||
localStorage.removeItem('accessToken_Internal');
|
||||
localStorage.removeItem('refreshToken_Internal');
|
||||
localStorage.removeItem('accessToken_OIDC');
|
||||
localStorage.removeItem('refreshToken_OIDC');
|
||||
this.getRxStompService().deactivate();
|
||||
if (this.oAuthService.clientId) {
|
||||
this.oAuthService.logOut();
|
||||
} else {
|
||||
this.router.navigate(['/login']);
|
||||
}
|
||||
}
|
||||
|
||||
getRxStompService(): RxStompService {
|
||||
|
||||
@@ -133,6 +133,5 @@ export class AppTopBarComponent implements OnDestroy {
|
||||
|
||||
logout() {
|
||||
this.authService.logout();
|
||||
window.location.href = '/login';
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user