Spring Security安全配置方法

CoolWill +0/-0 0 0 正常 2025-12-24T07:01:19 Spring Security · 认证授权 · 安全配置

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();

最佳实践建议

  1. 严格控制权限粒度,避免过度授权
  2. 启用HTTPS强制加密传输
  3. 定期更新依赖版本,防范已知漏洞
  4. 合理配置会话管理策略

通过以上配置,可以构建一个相对完善的安全防护体系。

推广
广告位招租

讨论

0/2000
秋天的童话
秋天的童话 · 2026-01-08T10:24:58
Spring Security配置核心在于filterChain链式调用,别被默认配置迷惑,要明确每个请求的授权路径,比如将/api/v1/public/**设为permitAll,而/api/v1/admin/**限定ADMIN角色,避免因权限粒度不够导致安全漏洞。
梦里水乡
梦里水乡 · 2026-01-08T10:24:58
自定义UserDetailsService是认证关键,建议直接注入Repository而不是在Service层做复杂逻辑,同时记得对密码进行BCrypt编码处理,别用明文或简单MD5,这是安全配置中最容易出错的点。