Spring Security入门指南
一、安全过滤器链核心原理
Spring Security的本质是过滤器链(Filter Chain),请求需经过20+内置过滤器的层层校验。以下是核心过滤器示例:
@Configuration
@EnableWebSecurity
public class BankSecurityConfig extends WebSecurityConfigurerAdapter {
// 配置HTTP安全规则
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable() // 生产环境需开启
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.antMatchers("/account/**").hasRole("USER")
.antMatchers("/admin/**").hasRole("ADMIN")
.and()
.formLogin()
.loginPage("/custom-login") // 自定义登录页
.loginProcessingUrl("/perform_login")
.and()
.rememberMe()
.key("bankAppSecretKey") // 记住我功能密钥
.and()
.logout()
.logoutSuccessUrl("/logout_success");
}
// 内存用户配置(生产需用数据库)
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER")
.and()
.withUser("admin").password("{noop}admin123").roles("ADMIN");
}
}
关键过滤器解析:
- SecurityContextPersistenceFilter:在请求间存储安全上下文
- UsernamePasswordAuthenticationFilter:处理表单登录
- FilterSecurityInterceptor:执行访问决策
- ExceptionTranslationFilter:处理认证异常
二、认证体系实战:JWT+OAuth2案例
2.1 JWT令牌生成配置
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("bank-secret-key"); // HS256对称加密
return converter;
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
2.2 OAuth2资源服务器配置
@Configuration
@EnableResourceServer
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/v1/transactions/**").access("#oauth2.hasScope('transaction')");
}
}
2.3 自定义用户权限验证
@Service
public class BankUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) {
User user = userRepository.findByUsername(username);
return new org.springframework.security.core.userdetails.User(
user.getUsername(),
user.getPassword(),
getAuthority(user.getRoles())
);
}
private Collection<? extends GrantedAuthority> getAuthority(Set<Role> roles) {
return roles.stream()
.map(role -> new SimpleGrantedAuthority("ROLE_" + role.getName()))
.collect(Collectors.toList());
}
}
三、企业级安全防护策略
3.1 CSRF防护最佳实践
http.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringAntMatchers("/api/**"); // API接口禁用CSRF
3.2 CORS跨域安全配置
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Arrays.asList(""));
config.setAllowedMethods(Arrays.asList("GET","POST"));
config.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
3.3 权限表达式高级用法
@PreAuthorize("hasRole('TELLER') and @bankSecurityService.isSameBranch(authentication, #accountId)")
public Account getAccountDetails(String accountId) {
// 柜员只能操作本支行账户
}
四、安全审计与监控
五、微服务安全架构
网关集中认证
// 网关统一鉴权配置
public class ApiGatewayFilter implements GatewayFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String token = extractJwt(exchange.getRequest());
if (token != null && jwtUtil.validateToken(token)) {
return chain.filter(exchange);
}
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
}
}
服务间认证
// Feign客户端携带JWT
@Bean
public RequestInterceptor requestInterceptor() {
return requestTemplate -> {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
String token = (String) authentication.getCredentials();
requestTemplate.header("Authorization", "Bearer " + token);
}
};
}
总结
核心安全原则
- 最小权限原则:用户只拥有必需权限
- 纵深防御:多层安全防护机制
- 零信任模型:永不默认信任任何请求
建议
- 定期轮换加密密钥(推荐使用Java KeyStore)
- 启用Spring Security的HTTP安全头部
- 集成OWASP Dependency-Check进行依赖扫描
- 强制HTTPS连接