package run.webup.platform; import jakarta.servlet.*; import jakarta.servlet.http.*; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.*; import org.springframework.context.annotation.*; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher; import org.springframework.web.filter.OncePerRequestFilter; @Configuration @EnableMethodSecurity public class SecurityConfig { public record Identity(UUID id, UUID sessionId, String email) {} public static String hash(String s) { try { return HexFormat.of() .formatHex( MessageDigest.getInstance("SHA-256").digest(s.getBytes(StandardCharsets.UTF_8))); } catch (Exception e) { throw new IllegalStateException(e); } } @Bean BCryptPasswordEncoder passwords() { return new BCryptPasswordEncoder(12); } @Bean SecurityFilterChain security(HttpSecurity http, JdbcTemplate db) throws Exception { var pluginFrame = PathPatternRequestMatcher.withDefaults() .matcher("/api/public/extensions/plugin-frame/{id}"); // Authorization header only: no cookie authentication and no browser auto-attached credentials. http.csrf(c -> c.disable()) .headers( h -> h.frameOptions(f -> f.disable()) .addHeaderWriter( (request, response) -> response.setHeader( "X-Frame-Options", pluginFrame.matches(request) ? "SAMEORIGIN" : "DENY"))) .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .authorizeHttpRequests( a -> a.requestMatchers( "/api/public/**", "/api/auth/captcha", "/api/auth/login", "/api/auth/register", "/actuator/health") .permitAll() .anyRequest() .authenticated()) .exceptionHandling( e -> e.authenticationEntryPoint( (q, r, x) -> { r.setStatus(401); r.setContentType("application/json;charset=UTF-8"); r.getWriter().write("{\"message\":\"请登录后继续\"}"); }) .accessDeniedHandler( (q, r, x) -> { r.setStatus(403); r.setContentType("application/json;charset=UTF-8"); r.getWriter().write("{\"message\":\"没有执行此操作的权限\"}"); })); http.addFilterBefore( new OncePerRequestFilter() { protected void doFilterInternal( HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException { String h = req.getHeader("Authorization"); if (h != null && h.startsWith("Bearer ") && h.length() < 300) { var sessions = db.queryForList( "SELECT s.id,s.user_id,u.email FROM user_sessions s JOIN users u ON" + " u.id=s.user_id WHERE s.token_hash=? AND s.revoked_at IS NULL AND" + " s.expires_at>CURRENT_TIMESTAMP AND u.status='ACTIVE'", hash(h.substring(7))); if (!sessions.isEmpty()) { var s = sessions.getFirst(); UUID uid = UUID.fromString(s.get("user_id").toString()); var perms = db.queryForList( "SELECT DISTINCT rp.permission_code FROM user_roles ur JOIN" + " role_permissions rp ON rp.role_code=ur.role_code WHERE" + " ur.user_id=?", String.class, uid); var authorities = new ArrayList(); perms.forEach(p -> authorities.add(new SimpleGrantedAuthority(p))); db.queryForList( "SELECT role_code FROM user_roles WHERE user_id=?", String.class, uid) .forEach(p -> authorities.add(new SimpleGrantedAuthority("ROLE_" + p))); var who = new Identity( uid, UUID.fromString(s.get("id").toString()), s.get("email").toString()); SecurityContextHolder.getContext() .setAuthentication( new UsernamePasswordAuthenticationToken(who, null, authorities)); } } try { chain.doFilter(req, res); } finally { SecurityContextHolder.clearContext(); } } }, UsernamePasswordAuthenticationFilter.class); return http.build(); } }