欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > spring security 过滤器链使用

spring security 过滤器链使用

2025/4/8 23:04:34 来源:https://blog.csdn.net/LCY133/article/details/147016352  浏览:    关键词:spring security 过滤器链使用

Spring Security 的过滤器链提供了灵活的安全控制机制,以下是其在实际开发中的 常见用法 及对应的过滤器配置示例:


一、认证方式配置

1. 表单登录认证

过滤器UsernamePasswordAuthenticationFilter
配置

http.formLogin().loginPage("/login")          // 自定义登录页.loginProcessingUrl("/auth")  // 登录处理路径.defaultSuccessUrl("/home")   // 登录成功跳转.failureUrl("/login?error");  // 登录失败跳转
2. JWT 令牌认证

自定义过滤器:解析请求头中的 JWT Token

public class JwtAuthFilter extends OncePerRequestFilter {@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) {String token = request.getHeader("Authorization");if (validateToken(token)) {Authentication auth = createAuthentication(token);SecurityContextHolder.getContext().setAuthentication(auth);}chain.doFilter(request, response);}
}

注册过滤器

http.addFilterBefore(new JwtAuthFilter(), UsernamePasswordAuthenticationFilter.class);
3. OAuth2 社交登录

依赖过滤器OAuth2AuthorizationRequestRedirectFilterOAuth2LoginAuthenticationFilter
配置

http.oauth2Login().loginPage("/login").defaultSuccessUrl("/profile").userInfoEndpoint().userService(oauth2UserService);

二、安全防护配置

1. 禁用 CSRF 防护

适用场景:无状态 API 服务(如使用 JWT)

http.csrf().disable();
2. 启用 CORS 跨域支持

过滤器CorsFilter
配置

@Bean
CorsConfigurationSource corsConfigurationSource() {CorsConfiguration config = new CorsConfiguration();config.addAllowedOrigin("https://example.com");config.addAllowedMethod("*");config.addAllowedHeader("*");UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();source.registerCorsConfiguration("/**", config);return source;
}
3. 安全响应头配置

过滤器HeaderWriterFilter
配置

http.headers().contentSecurityPolicy("default-src 'self'").frameOptions().deny();

三、授权控制配置

1. 基于角色的访问控制

过滤器FilterSecurityInterceptor
配置

http.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN").antMatchers("/user/**").hasAnyRole("USER", "ADMIN").anyRequest().authenticated();
2. 方法级权限控制

启用注解

@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {}

使用注解

@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/admin/dashboard")
public String adminDashboard() { /* ... */ }

四、会话管理

1. 无状态会话(适用于 API)

配置

http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
2. 会话并发控制

配置

http.sessionManagement().maximumSessions(1)  // 每个用户最多一个会话.expiredUrl("/login?expired");

五、静态资源处理

1. 忽略静态资源

过滤器WebSecurity 配置

@Override
public void configure(WebSecurity web) {web.ignoring().antMatchers("/css/**", "/js/**", "/images/**");
}

六、异常处理

1. 自定义未认证响应

配置

http.exceptionHandling().authenticationEntryPoint((request, response, authException) -> {response.sendError(HttpStatus.UNAUTHORIZED.value(), "请先登录");});
2. 自定义无权限响应

配置

http.exceptionHandling().accessDeniedHandler((request, response, accessDeniedException) -> {response.sendError(HttpStatus.FORBIDDEN.value(), "权限不足");});

七、自定义过滤器链

1. 添加自定义过滤器
// 添加日志过滤器到链首
http.addFilterBefore(new RequestLoggingFilter(), SecurityContextPersistenceFilter.class);
2. 移除默认过滤器
// 禁用默认的 BasicAuthenticationFilter
http.httpBasic().disable();

总结

Spring Security 过滤器链的常见用法可归纳为以下场景:

场景关键过滤器/配置典型应用
表单登录UsernamePasswordAuthenticationFilter传统 Web 应用登录
API 令牌认证自定义 JWT/OAuth2 过滤器前后端分离架构
安全防护CsrfFilterCorsFilter防止 CSRF、配置跨域
细粒度授权FilterSecurityInterceptor基于 URL 或方法的权限控制
会话管理SessionManagementFilter控制会话创建策略和并发登录
静态资源WebSecurity.ignoring()加速 CSS/JS/图片加载

通过灵活组合这些配置,开发者可以快速实现从简单登录到复杂分布式系统的安全需求,同时保持代码的可维护性和扩展性。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词