Spring Security入门指南

原文:xuanhu.info/projects/it...

Spring Security入门指南

一、安全过滤器链核心原理

Spring Security的本质是过滤器链(Filter Chain),请求需经过20+内置过滤器的层层校验。以下是核心过滤器示例:

java 复制代码
@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");
    }
}

关键过滤器解析:

  1. SecurityContextPersistenceFilter:在请求间存储安全上下文
  2. UsernamePasswordAuthenticationFilter:处理表单登录
  3. FilterSecurityInterceptor:执行访问决策
  4. ExceptionTranslationFilter:处理认证异常

二、认证体系实战:JWT+OAuth2案例

2.1 JWT令牌生成配置

java 复制代码
@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资源服务器配置

java 复制代码
@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 自定义用户权限验证

java 复制代码
@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防护最佳实践

java 复制代码
http.csrf()
    .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
    .ignoringAntMatchers("/api/**"); // API接口禁用CSRF

3.2 CORS跨域安全配置

java 复制代码
@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 权限表达式高级用法

java 复制代码
@PreAuthorize("hasRole('TELLER') and @bankSecurityService.isSameBranch(authentication, #accountId)")
public Account getAccountDetails(String accountId) {
    // 柜员只能操作本支行账户
}

四、安全审计与监控

classDiagram class SecurityEvent{ +Long id +String username +String eventType +LocalDateTime timestamp +String ipAddress } class AuditService{ +logEvent(SecurityEvent event) +generateDailyReport() } SecurityEvent "1" --> "1..*" AuditService

五、微服务安全架构

::: tabs#微服务模式 @tab 网关集中认证

java 复制代码
// 网关统一鉴权配置
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();
    }
}

@tab 服务间认证

java 复制代码
// 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);
        }
    };
}

:::


总结

核心安全原则

  1. 最小权限原则:用户只拥有必需权限
  2. 纵深防御:多层安全防护机制
  3. 零信任模型:永不默认信任任何请求

建议

  • 定期轮换加密密钥(推荐使用Java KeyStore)
  • 启用Spring Security的HTTP安全头部
  • 集成OWASP Dependency-Check进行依赖扫描
  • 强制HTTPS连接

原文:xuanhu.info/projects/it...

相关推荐
想用offer打牌4 小时前
MCP (Model Context Protocol) 技术理解 - 第二篇
后端·aigc·mcp
KYGALYX5 小时前
服务异步通信
开发语言·后端·微服务·ruby
掘了5 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
爬山算法6 小时前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
Moment6 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
Cobyte7 小时前
AI全栈实战:使用 Python+LangChain+Vue3 构建一个 LLM 聊天应用
前端·后端·aigc
程序员侠客行8 小时前
Mybatis连接池实现及池化模式
java·后端·架构·mybatis
Honmaple8 小时前
QMD (Quarto Markdown) 搭建与使用指南
后端
PP东8 小时前
Flowable学习(二)——Flowable概念学习
java·后端·学习·flowable
invicinble8 小时前
springboot的核心实现机制原理
java·spring boot·后端