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

71 lines
2.9 KiB
Java
Raw Normal View History

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