将登录认证与会话管理交还 Spring Security

This commit is contained in:
2026-09-27 17:34:07 +00:00
parent a4b99d54f3
commit bccb331d8b
19 changed files with 347 additions and 400 deletions
@@ -1,50 +0,0 @@
package top.ddupan.iam.login.authentication.application;
import java.time.Clock;
import java.util.UUID;
import top.ddupan.iam.login.authentication.application.port.PasswordAuthenticator;
import top.ddupan.iam.login.authentication.domain.UserRepository;
import top.ddupan.iam.login.authentication.application.port.PasswordVerificationException;
import top.ddupan.iam.login.authentication.domain.LoginTransaction;
/** Coordinates the first-factor use case. HTTP/session/LDAP details stay in adapters. */
public final class SignInService {
public enum PasswordResult { ACCEPTED, REJECTED, EXPIRED, WRONG_STEP, RETRY_LATER }
private final PasswordAuthenticator authenticator;
private final Clock clock;
private final boolean enabled;
public SignInService(PasswordAuthenticator authenticator, Clock clock, boolean enabled) {
this.authenticator = authenticator;
this.clock = clock;
this.enabled = enabled;
}
public boolean enabled() { return enabled; }
public LoginTransaction start() { return LoginTransaction.start(UUID.randomUUID(), clock.instant()); }
public boolean expired(LoginTransaction transaction) { return transaction.expiredAt(clock.instant()); }
public PasswordResult submitPassword(LoginTransaction transaction, String username, String password) {
if (!enabled) throw new IllegalStateException("Human sign-in is disabled");
var attempt = transaction.beginPasswordAttempt(clock.instant());
if (attempt != LoginTransaction.Attempt.ALLOWED) {
return switch (attempt) {
case EXPIRED -> PasswordResult.EXPIRED;
case WRONG_STEP -> PasswordResult.WRONG_STEP;
case RETRY_LATER -> PasswordResult.RETRY_LATER;
case ALLOWED -> throw new IllegalStateException("Unexpected attempt result");
};
}
try (var session = authenticator.authenticate(username, password)) {
var identity = session.users().findByLoginName(session.loginName());
if (identity.isEmpty()) return PasswordResult.REJECTED;
// A slow directory response must not revive an expired transaction.
var verifiedAt = clock.instant();
if (transaction.expiredAt(verifiedAt)) return PasswordResult.EXPIRED;
transaction.passwordVerified(identity.orElseThrow(), verifiedAt);
return PasswordResult.ACCEPTED;
} catch (PasswordVerificationException | UserRepository.AccessFailure ex) {
return PasswordResult.REJECTED;
}
}
}
@@ -0,0 +1,22 @@
package top.ddupan.iam.login.authentication.application;
import top.ddupan.iam.login.authentication.application.port.PasswordAuthenticator;
import top.ddupan.iam.login.authentication.application.port.PasswordVerificationException;
import top.ddupan.iam.login.authentication.application.port.PasswordVerificationException.Reason;
import top.ddupan.iam.login.authentication.domain.User;
/** Resolves the user through the same authenticated directory connection. */
public final class VerifyPassword {
private final PasswordAuthenticator authenticator;
public VerifyPassword(PasswordAuthenticator authenticator) {
this.authenticator = authenticator;
}
public User verify(String username, String password) {
try (var session = authenticator.authenticate(username, password)) {
return session.users().findByLoginName(session.loginName())
.orElseThrow(() -> new PasswordVerificationException(Reason.REJECTED));
}
}
}
@@ -1,56 +0,0 @@
package top.ddupan.iam.login.authentication.domain;
import java.time.Duration;
import java.time.Instant;
import java.util.Objects;
import java.util.UUID;
/** Owns first-factor ordering, lifetime and the identity to which further factors must bind. */
public final class LoginTransaction {
private static final Duration LIFETIME = Duration.ofMinutes(10);
private static final Duration ATTEMPT_INTERVAL = Duration.ofSeconds(2);
public enum Step { PASSWORD_REQUIRED, MFA_REQUIRED }
public enum Attempt { ALLOWED, EXPIRED, WRONG_STEP, RETRY_LATER }
private final UUID id;
private Step step = Step.PASSWORD_REQUIRED;
private Instant expiresAt;
private Instant retryAfter = Instant.MIN;
private User identity;
private LoginTransaction(UUID id, Instant now) {
this.id = Objects.requireNonNull(id);
this.expiresAt = now.plus(LIFETIME);
}
public static LoginTransaction start(UUID id, Instant now) {
return new LoginTransaction(id, now);
}
public Attempt beginPasswordAttempt(Instant now) {
if (expiredAt(now)) return Attempt.EXPIRED;
if (step != Step.PASSWORD_REQUIRED) return Attempt.WRONG_STEP;
if (now.isBefore(retryAfter)) return Attempt.RETRY_LATER;
retryAfter = now.plus(ATTEMPT_INTERVAL);
return Attempt.ALLOWED;
}
public void passwordVerified(User identity, Instant now) {
if (expiredAt(now) || step != Step.PASSWORD_REQUIRED) {
throw new IllegalStateException("Password verification is not allowed in this transaction state");
}
this.identity = Objects.requireNonNull(identity);
this.step = Step.MFA_REQUIRED;
this.expiresAt = now.plus(LIFETIME);
}
public UUID id() { return id; }
public Step step() { return step; }
public boolean expiredAt(Instant now) { return !now.isBefore(expiresAt); }
public User identity() {
if (identity == null) throw new IllegalStateException("No verified identity yet");
return identity;
}
}
@@ -0,0 +1,44 @@
package top.ddupan.iam.login.authentication.infrastructure.security;
import java.util.List;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.FactorGrantedAuthority;
import top.ddupan.iam.login.authentication.application.VerifyPassword;
import top.ddupan.iam.login.authentication.application.port.PasswordVerificationException;
import top.ddupan.iam.login.authentication.domain.UserRepository;
/** Bridges directory authentication into Spring Security's form-login lifecycle. */
public final class DirectoryAuthenticationProvider implements AuthenticationProvider {
private final VerifyPassword passwords;
public DirectoryAuthenticationProvider(VerifyPassword passwords) {
this.passwords = passwords;
}
@Override
public Authentication authenticate(Authentication request) {
try {
var user = passwords.verify(request.getName(),
request.getCredentials() instanceof String password ? password : null);
// Directory groups remain profile data, not local application authorities.
return UsernamePasswordAuthenticationToken.authenticated(new DirectoryPrincipal(user), null,
List.of(FactorGrantedAuthority.fromAuthority(FactorGrantedAuthority.PASSWORD_AUTHORITY)));
} catch (PasswordVerificationException ex) {
if (ex.reason() == PasswordVerificationException.Reason.UNAVAILABLE) {
throw new InternalAuthenticationServiceException("Directory unavailable");
}
throw new BadCredentialsException("Unable to verify credentials");
} catch (UserRepository.AccessFailure ex) {
throw new InternalAuthenticationServiceException("Directory unavailable");
}
}
@Override
public boolean supports(Class<?> authentication) {
return UsernamePasswordAuthenticationToken.class.equals(authentication);
}
}
@@ -0,0 +1,12 @@
package top.ddupan.iam.login.authentication.infrastructure.security;
import org.springframework.security.core.AuthenticatedPrincipal;
import top.ddupan.iam.login.authentication.domain.User;
/** An immutable directory snapshot; never contains credentials or connections. */
public record DirectoryPrincipal(User user) implements AuthenticatedPrincipal {
@Override
public String getName() {
return user.id().authority() + ":" + user.id().value();
}
}
@@ -1,12 +0,0 @@
package top.ddupan.iam.login.authentication.interfaces.web;
import top.ddupan.iam.login.authentication.domain.LoginTransaction;
/** HTTP-session storage plus presentation feedback. Authentication rules live in the aggregate. */
final class BrowserSignInState {
final LoginTransaction transaction;
String username = "";
String error = "";
BrowserSignInState(LoginTransaction transaction) { this.transaction = transaction; }
}
@@ -27,6 +27,6 @@ public class PageRenderer {
.replace(">", "\\u003e").replace("&", "\\u0026")
.replace("\u2028", "\\u2028").replace("\u2029", "\\u2029");
return ResponseEntity.ok().header("Cache-Control", "no-store")
.contentType(MediaType.TEXT_HTML).body(shell.replace(SLOT, safe));
.contentType(new MediaType(MediaType.TEXT_HTML, StandardCharsets.UTF_8)).body(shell.replace(SLOT, safe));
}
}
@@ -0,0 +1,35 @@
package top.ddupan.iam.login.authentication.interfaces.web;
import java.io.IOException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;
/** Rejects disabled or plaintext sign-in before any credentials reach authentication. */
public final class SignInAvailabilityFilter extends OncePerRequestFilter {
private final boolean enabled;
public SignInAvailabilityFilter(boolean enabled) {
this.enabled = enabled;
}
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
String path = request.getServletPath();
if (path.isEmpty()) path = request.getRequestURI().substring(request.getContextPath().length());
return !path.equals("/signin") && !path.startsWith("/signin/");
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
if (!enabled || !request.isSecure()) {
response.setHeader("Cache-Control", "no-store");
response.setStatus(enabled ? 426 : 404);
return;
}
chain.doFilter(request, response);
}
}
@@ -1,118 +1,44 @@
package top.ddupan.iam.login.authentication.interfaces.web;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import top.ddupan.iam.login.authentication.application.SignInService;
import top.ddupan.iam.login.authentication.domain.LoginTransaction.Step;
import top.ddupan.iam.login.authentication.domain.User.GroupMembership;
import top.ddupan.iam.login.authentication.infrastructure.security.DirectoryPrincipal;
/** Translates browser requests and use-case outcomes; no directory or authentication policy here. */
/** Renders Spring Security's login pages; form processing belongs to the security filters. */
@RestController
public class SignInController {
static final String STATE = SignInController.class.getName() + ".state";
private final SignInService signIn;
private final PageRenderer renderer;
public SignInController(SignInService signIn, PageRenderer renderer) {
this.signIn = signIn;
public SignInController(PageRenderer renderer) {
this.renderer = renderer;
}
@GetMapping(value = "/signin", produces = MediaType.TEXT_HTML_VALUE)
ResponseEntity<String> page(HttpServletRequest request, CsrfToken csrf) {
requireAvailable(request);
var session = request.getSession();
synchronized (session) {
var state = state(session);
if (state.transaction.step() == Step.MFA_REQUIRED) return redirect("/signin/mfa");
return renderer.render(Map.of("step", "password", "name", state.username,
"error", state.error, "action", "/signin/password", "csrf", csrf(csrf)));
}
}
@PostMapping("/signin/password")
ResponseEntity<String> password(HttpServletRequest request,
@RequestParam(defaultValue = "") String username,
@RequestParam(defaultValue = "") String password) {
requireAvailable(request);
var session = request.getSession(false);
if (session == null) throw new ResponseStatusException(HttpStatus.CONFLICT);
synchronized (session) {
var state = (BrowserSignInState) session.getAttribute(STATE);
if (state == null) return redirect("/signin");
state.username = username.length() <= 256 ? username : "";
return switch (signIn.submitPassword(state.transaction, username, password)) {
case ACCEPTED -> {
request.changeSessionId();
state.error = "";
yield redirect("/signin/mfa");
}
case REJECTED -> {
state.error = "无法验证账号,请检查凭据与账号状态,或稍后重试。";
yield redirect("/signin");
}
case EXPIRED, WRONG_STEP -> redirect("/signin");
case RETRY_LATER -> throw new ResponseStatusException(HttpStatus.TOO_MANY_REQUESTS);
};
}
ResponseEntity<String> page(@RequestParam(required = false) String error, CsrfToken csrf) {
return renderer.render(Map.of("step", "password", "name", "",
"error", error == null ? "" : "无法验证账号,请检查凭据与账号状态,或稍后重试。",
"action", "/signin/password", "csrf", csrf(csrf)));
}
@GetMapping(value = "/signin/mfa", produces = MediaType.TEXT_HTML_VALUE)
ResponseEntity<String> pending(HttpServletRequest request, CsrfToken csrf) {
requireAvailable(request);
var session = request.getSession(false);
if (session == null) return redirect("/signin");
synchronized (session) {
var state = state(session);
if (state.transaction.step() != Step.MFA_REQUIRED) return redirect("/signin");
var user = state.transaction.identity();
return renderer.render(Map.of("step", "mfa-pending", "name", user.displayName(),
"error", "", "action", "/signin/restart", "csrf", csrf(csrf),
"identity", Map.of("username", user.username(), "subjectId", user.id().value(),
"email", user.email(),
"groups", user.memberships().stream().map(GroupMembership::name).toList(),
"groupDns", user.memberships().stream().map(GroupMembership::externalId).toList())));
}
}
@PostMapping("/signin/restart")
ResponseEntity<String> restart(HttpServletRequest request) {
requireAvailable(request);
var session = request.getSession(false);
if (session != null) session.invalidate();
return redirect("/signin");
}
private void requireAvailable(HttpServletRequest request) {
if (!signIn.enabled()) throw new ResponseStatusException(HttpStatus.NOT_FOUND);
if (!request.isSecure()) throw new ResponseStatusException(HttpStatus.UPGRADE_REQUIRED, "HTTPS required");
}
private BrowserSignInState state(HttpSession session) {
var state = (BrowserSignInState) session.getAttribute(STATE);
if (state == null || signIn.expired(state.transaction)) {
state = new BrowserSignInState(signIn.start());
session.setAttribute(STATE, state);
}
return state;
ResponseEntity<String> pending(@AuthenticationPrincipal DirectoryPrincipal principal, CsrfToken csrf) {
var user = principal.user();
return renderer.render(Map.of("step", "mfa-pending", "name", user.displayName(),
"error", "", "action", "/signin/restart", "csrf", csrf(csrf),
"identity", Map.of("username", user.username(), "subjectId", user.id().value(),
"email", user.email(),
"groups", user.memberships().stream().map(GroupMembership::name).toList(),
"groupDns", user.memberships().stream().map(GroupMembership::externalId).toList())));
}
private static Map<String, String> csrf(CsrfToken token) {
return Map.of("name", token.getParameterName(), "value", token.getToken());
}
private static ResponseEntity<String> redirect(String location) {
return ResponseEntity.status(HttpStatus.SEE_OTHER).header("Location", location)
.header("Cache-Control", "no-store").build();
}
}
@@ -1,6 +1,5 @@
package top.ddupan.iam.login.configuration;
import java.time.Clock;
import javax.naming.directory.DirContext;
import javax.naming.ldap.LdapContext;
import org.springframework.aot.hint.RuntimeHints;
@@ -11,9 +10,8 @@ import org.springframework.ldap.core.DirContextProxy;
import top.ddupan.iam.login.authentication.infrastructure.ad.AdUserEntry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import top.ddupan.iam.login.authentication.application.SignInService;
import top.ddupan.iam.login.authentication.application.VerifyPassword;
import top.ddupan.iam.login.authentication.application.port.PasswordAuthenticator;
import top.ddupan.iam.login.authentication.infrastructure.ad.AdProperties;
/** Composition root: dependencies point inward, framework wiring stays outside the model. */
@Configuration(proxyBeanMethods = false)
@@ -21,8 +19,8 @@ import top.ddupan.iam.login.authentication.infrastructure.ad.AdProperties;
@ImportRuntimeHints(AuthenticationConfiguration.DirectoryHints.class)
class AuthenticationConfiguration {
@Bean
SignInService signInService(PasswordAuthenticator authenticator, AdProperties properties) {
return new SignInService(authenticator, Clock.systemUTC(), properties.enabled());
VerifyPassword verifyPassword(PasswordAuthenticator authenticator) {
return new VerifyPassword(authenticator);
}
static class DirectoryHints implements RuntimeHintsRegistrar {
@Override
@@ -1,19 +1,68 @@
package top.ddupan.iam.login.configuration;
import java.time.Duration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authorization.AuthorizationManagerFactories;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.authorization.EnableMultiFactorAuthentication;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
import top.ddupan.iam.login.authentication.application.VerifyPassword;
import top.ddupan.iam.login.authentication.infrastructure.ad.AdProperties;
import top.ddupan.iam.login.authentication.infrastructure.security.DirectoryAuthenticationProvider;
import top.ddupan.iam.login.authentication.interfaces.web.SignInAvailabilityFilter;
@Configuration(proxyBeanMethods = false)
@EnableMultiFactorAuthentication(authorities = {})
class SecurityConfiguration {
// Operational Basic authentication is isolated from human first-factor authentication.
@Bean
SecurityFilterChain security(HttpSecurity http) throws Exception {
return http.authorizeHttpRequests(auth -> auth
.requestMatchers("/error", "/signin", "/signin/**", "/assets/**", "/actuator/health/**").permitAll()
@Order(1)
SecurityFilterChain management(HttpSecurity http) throws Exception {
return http.securityMatcher("/actuator/**")
.authorizeHttpRequests(auth -> auth
.requestMatchers("/actuator/health/**").permitAll()
.anyRequest().authenticated())
.securityContext(context -> context.securityContextRepository(
new org.springframework.security.web.context.NullSecurityContextRepository()))
.sessionManagement(session -> session.sessionCreationPolicy(
org.springframework.security.config.http.SessionCreationPolicy.STATELESS))
.httpBasic(Customizer.withDefaults())
.build();
}
@Bean
@Order(2)
SecurityFilterChain browser(HttpSecurity http, VerifyPassword passwords, AdProperties ad) throws Exception {
var passwordFactor = AuthorizationManagerFactories.<RequestAuthorizationContext>multiFactor()
.requireFactor(factor -> factor.passwordAuthority().validDuration(Duration.ofMinutes(10)))
.build();
return http
.authenticationManager(new ProviderManager(new DirectoryAuthenticationProvider(passwords)))
.addFilterBefore(new SignInAvailabilityFilter(ad.enabled()), CsrfFilter.class)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/error", "/signin", "/signin/password", "/assets/**").permitAll()
.requestMatchers("/signin/mfa").access(passwordFactor.authenticated())
// No complete MFA or Hydra acceptance exists yet. Fail closed until those are implemented.
.anyRequest().denyAll())
.formLogin(form -> form.loginPage("/signin").loginProcessingUrl("/signin/password")
.defaultSuccessUrl("/signin/mfa", true).failureUrl("/signin?error"))
.logout(logout -> logout.logoutUrl("/signin/restart").logoutSuccessUrl("/signin"))
.exceptionHandling(exceptions -> exceptions
.defaultAuthenticationEntryPointFor(new LoginUrlAuthenticationEntryPoint("/signin"),
PathPatternRequestMatcher.withDefaults().matcher("/signin/**"))
.defaultAuthenticationEntryPointFor(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED),
org.springframework.security.web.util.matcher.AnyRequestMatcher.INSTANCE))
.requestCache(cache -> cache.disable())
.headers(headers -> headers.contentSecurityPolicy(csp -> csp.policyDirectives(
"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; "
+ "object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'")))