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...

相关推荐
一条Go3 分钟前
全链路 e2e:一次跑出 20 个现象,收敛成 5 个根因
后端·github·测试
让我们一起加油好吗5 分钟前
【算法刷题】LeetCode 力扣 Hot 100 刷题记录
数据结构·c++·算法·leetcode·面试·笔试
Rain的Java大神之路17 分钟前
LeetCode 42「接雨水」:面试官百出不厌的题,一文讲透从暴力到双指针 O(1)
java·后端·leetcode
崖边看雾1 小时前
Kafka 手册
分布式·面试·kafka
会编程的吕洞宾2 小时前
Kafka消费者组重平衡实战:重复消费与消费停顿排查
java·经验分享·后端
Wellijohn2 小时前
`s += x` 到底是 O(n) 还是 O(n²)?我把 CPython 的字符串拼接拆开测了一遍
后端·python·性能优化
IT空门:门主11 小时前
Spring AI 2.1.0 更新了什么:从 2.0 升上来的完整梳理
人工智能·python·spring
思想觉悟11 小时前
Aosp实战之自定义开机启动进程
c++·面试
努力的小雨14 小时前
手里捏着纸,谁来暂停视频?我把折纸老师塞进了 AI 眼镜
后端
狗头大军之江苏分军14 小时前
《潮水漫过十七岁》倒计时
前端·javascript·后端