yl-backend/src/main/java/com/guwan/backend/config/SecurityConfig.java

71 lines
2.9 KiB
Java

package com.guwan.backend.config;
import com.guwan.backend.constant.SecurityConstants;
import com.guwan.backend.security.JwtAuthenticationFilter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
/**
* Spring Security 安全配置类
* 配置安全相关的全局策略
*/
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final JwtAuthenticationFilter jwtAuthFilter;
/**
* 配置安全过滤链
* 定义了系统的安全策略,包括:
* 1. CSRF 和 CORS 配置
* 2. Session 管理策略
* 3. 请求授权规则
* 4. JWT 过滤器配置
*/
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable) // 禁用CSRF保护
.cors(AbstractHttpConfigurer::disable) // 禁用CORS保护
.sessionManagement(session ->
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) // 使用无状态会话
.authorizeHttpRequests(auth -> auth
.requestMatchers(SecurityConstants.WHITE_LIST.toArray(new String[0])).permitAll() // 配置API白名单
.requestMatchers(SecurityConstants.STATIC_RESOURCES.toArray(new String[0])).permitAll() // 配置静态资源白名单
.anyRequest().authenticated() // 其他所有请求都需要认证
)
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class); // 添加JWT过滤器
return http.build();
}
/**
* 认证管理器
*/
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
return config.getAuthenticationManager();
}
/**
* 密码编码器
* 使用 BCrypt 加密算法
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}