1. 概述
Spring Security框架提供了WebSecurity
和HttpSecurity
两个核心类,用于实现全局级别和资源级别的安全控制。WebSecurity
负责配置全局安全策略,而HttpSecurity
则专注于为特定资源设置安全规则。
本文将深入探讨这两个类的核心用法,并对比它们的差异。理解这两者的区别,能帮你更精准地控制Spring Security的行为。
2. HttpSecurity
详解
HttpSecurity
类用于配置特定HTTP请求的安全策略。它支持通过requestMatcher()
方法将安全配置限定到特定接口,还能灵活实现基于角色的访问控制。
2.1 基础用法
以下代码展示如何用HttpSecurity
限制/admin/**
接口的访问权限:
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests((authorize) -> authorize.requestMatchers("/admin/**")
.authenticated()
.anyRequest()
.permitAll())
.formLogin(withDefaults());
return http.build();
}
这段代码的核心逻辑:
- ✅
/admin/**
路径需要认证 - ✅ 其他所有请求允许匿名访问
- ✅ 启用默认表单登录
2.2 角色控制
通过hasRole()
方法可以轻松实现基于角色的访问控制:
// ...
http.authorizeHttpRequests((authorize) -> authorize.requestMatchers("/admin/**").hasRole("ADMIN")
// ...
现在只有拥有ADMIN
角色的用户才能访问/admin/**
接口,安全等级显著提升。
2.3 扩展功能
HttpSecurity
还支持配置:
这些功能在构建RESTful API时特别实用。
3. WebSecurity
详解
WebSecurity
用于配置全局级别的安全策略,通过暴露WebSecurityCustomizer
Bean实现自定义。与HttpSecurity
不同,它的配置会应用到所有请求和资源。
3.1 ignoring()
方法
ignoring()
方法可以完全绕过Spring Security过滤器链,适用于静态资源:
@Bean
WebSecurityCustomizer ignoringCustomizer() {
return (web) -> web.ignoring().requestMatchers("/resources/**", "/static/**");
}
⚠️ 重要提醒:
- ✅ 仅用于静态资源(CSS、图片等)
- ❌ 切勿用于动态接口!这会完全跳过安全检查
- ❌ 可能导致CSRF、SQL注入等攻击风险
3.2 debug()
方法
启用调试日志,帮助排查安全配置问题:
@Bean
WebSecurityCustomizer debugSecurity() {
return (web) -> web.debug(true);
}
开启后会在控制台输出详细的安全过滤器日志,调试时特别有用。
3.3 httpFirewall()
方法
配置HTTP防火墙,限制允许的HTTP方法:
@Bean
HttpFirewall allowHttpMethod() {
List<String> allowedMethods = new ArrayList<String>();
allowedMethods.add("GET");
allowedMethods.add("POST");
StrictHttpFirewall firewall = new StrictHttpFirewall();
firewall.setAllowedHttpMethods(allowedMethods);
return firewall;
}
@Bean
WebSecurityCustomizer fireWall() {
return (web) -> web.httpFirewall(allowHttpMethod());
}
默认允许DELETE/GET/HEAD/OPTIONS/PATCH/POST/PUT,本例只允许GET和POST。其他方法会直接返回HTTP错误。
4. 核心差异对比
WebSecurity
和HttpSecurity
可以协同工作,但需注意优先级:
@Bean
WebSecurityCustomizer ignoringCustomizer() {
return (web) -> web.ignoring().antMatchers("/admin/**");
}
// ...
http.authorizeHttpRequests((authorize) -> authorize.antMatchers("/admin/**").hasRole("ADMIN")
// ...
这里WebSecurity
的ignoring()
配置会覆盖HttpSecurity
的授权规则,导致/admin/**
完全开放!
差异总结表
特性 | WebSecurity |
HttpSecurity |
---|---|---|
作用范围 | 全局默认规则 | 特定资源规则 |
典型场景 | 防火墙配置、静态资源忽略、调试模式 | URL规则、授权控制、CORS/CSRF |
配置方式 | 全局可复用配置 | 按资源条件配置 |
执行优先级 | ⚠️ 更高(过滤器链优先执行) | 较低 |
5. 总结
本文通过示例代码详细解析了HttpSecurity
和WebSecurity
的核心用法:
HttpSecurity
:精细控制特定资源的安全策略WebSecurity
:全局配置默认安全规则
两者结合使用,可以构建出既灵活又安全的Spring应用。实际开发中建议:
- 用
WebSecurity
处理全局性配置(如静态资源、防火墙) - 用
HttpSecurity
实现业务相关的细粒度访问控制
完整示例代码可在GitHub获取。