package com.example.rzgb.auth; import java.util.List; import java.util.UUID; import com.example.rzgb.config.AppProperties; import org.springframework.boot.ApplicationRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.core.userdetails.*; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import jakarta.servlet.DispatcherType; import jakarta.servlet.http.HttpServletResponse; /** 使用 Spring Security 的会话固定攻击防护、密码哈希及 CSRF;不自制登录 token。 */ @Configuration public class SecurityConfig { @Bean PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean UserDetailsService users(JdbcTemplate jdbc) { return username -> { List users = jdbc.query("SELECT username,password_hash FROM app_user WHERE username=?", (rs, row) -> User.withUsername(rs.getString(1)).password(rs.getString(2)).roles("ADMIN").build(), username); if (users.isEmpty()) throw new UsernameNotFoundException("账号或密码错误"); return users.getFirst(); }; } @Bean ApplicationRunner initializeAdmin(JdbcTemplate jdbc, PasswordEncoder encoder, AppProperties p) { return args -> { if (jdbc.queryForObject("SELECT COUNT(*) FROM app_user WHERE username='admin'", Integer.class) == 0) { // 初始密码由部署者指定,不限制最小长度;已有 admin 时不会覆盖其密码。 // 拒绝空白配置,避免漏配后创建空密码账号;72 字节是 BCrypt 的算法上限,按 UTF-8 字节检查。 if (p.adminPassword() == null || p.adminPassword().isBlank() || p.adminPassword().getBytes(java.nio.charset.StandardCharsets.UTF_8).length > 72) throw new IllegalStateException("首次启动须设置 ADMIN_INITIAL_PASSWORD(不能为空,UTF-8 不超过 72 字节)"); jdbc.update("INSERT INTO app_user(id,username,password_hash) VALUES(?,?,?)", UUID.randomUUID().toString(), "admin", encoder.encode(p.adminPassword())); } }; } @Bean SecurityFilterChain security(HttpSecurity http) throws Exception { // 默认会话 CSRF 仓库与 XOR token 配套。前端 GET /auth/csrf 后原样回传 header, // 登录与退出后重新取得 token;不关闭登录接口的 CSRF 检查。 http.authorizeHttpRequests(a -> a.dispatcherTypeMatchers(DispatcherType.ASYNC, DispatcherType.ERROR).permitAll() .requestMatchers("/api/auth/csrf", "/api/auth/login", "/actuator/health").permitAll() .anyRequest().authenticated()) .formLogin(f -> f.loginProcessingUrl("/api/auth/login") .successHandler((req, res, auth) -> reply(res, 200, "{\"username\":\"admin\"}")) .failureHandler((req, res, e) -> reply(res, 401, "{\"code\":\"INVALID_CREDENTIALS\",\"message\":\"账号或密码错误\"}"))) .logout(l -> l.logoutUrl("/api/auth/logout").invalidateHttpSession(true).deleteCookies("JSESSIONID") .logoutSuccessHandler((req, res, auth) -> reply(res, 200, "{}"))) .exceptionHandling(e -> e.authenticationEntryPoint((req, res, ex) -> reply(res, 401, "{\"code\":\"UNAUTHENTICATED\",\"message\":\"请先登录\"}")) .accessDeniedHandler((req, res, ex) -> reply(res, 403, "{\"code\":\"FORBIDDEN\",\"message\":\"会话校验失败,请刷新后重试\"}"))); return http.build(); } private static void reply(HttpServletResponse res, int status, String json) throws java.io.IOException { res.setStatus(status); res.setContentType("application/json;charset=UTF-8"); res.getWriter().write(json); } }