Spring Security安全配置方法
Spring Security作为Java生态中最主流的安全框架,其配置方法直接影响应用的安全性。本文将从实际工程角度,分享几种常见的安全配置实践。
基础安全配置
首先需要引入Spring Security依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
基础配置类示例:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authz -> authz
.requestMatchers("/public/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.formLogin(withDefaults())
.logout(logout -> logout.logoutSuccessUrl("/login"));
return http.build();
}
}
用户认证配置
通过自定义UserDetailsService实现用户验证:
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 从数据库加载用户信息
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User not found");
}
return org.springframework.security.core.userdetails.User.builder()
.username(user.getUsername())
.password(user.getPassword())
.authorities(user.getRoles())
.build();
}
}
CORS和CSRF防护
生产环境建议启用CORS配置:
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("https://trusted-domain.com"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
configuration.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
配置完成后,通过http.cors()启用:
http.cors().and().csrf().disable();
最佳实践建议
- 严格控制权限粒度,避免过度授权
- 启用HTTPS强制加密传输
- 定期更新依赖版本,防范已知漏洞
- 合理配置会话管理策略
通过以上配置,可以构建一个相对完善的安全防护体系。

讨论