题目
Spring Security基本配置:如何保护所有URL但放行静态资源?
信息
- 类型:问答
- 难度:⭐
考点
安全配置,静态资源放行,认证机制
快速回答
在Spring Security中配置保护所有URL但放行静态资源的步骤:
- 创建配置类继承
WebSecurityConfigurerAdapter - 重写
configure(HttpSecurity http)方法 - 使用
authorizeRequests()配置访问规则:antMatchers("/css/**", "/js/**").permitAll()放行静态资源anyRequest().authenticated()要求其他所有请求认证
- 启用表单登录:
formLogin()
原理说明
Spring Security通过过滤器链处理HTTP请求。配置类中的 HttpSecurity 对象允许我们定义URL访问规则:
- 认证保护:
anyRequest().authenticated()要求对所有请求进行身份验证 - 资源放行:
antMatchers().permitAll()指定无需认证的URL模式 - 执行顺序:规则按声明顺序生效,需先放行静态资源再设置全局保护
代码示例
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
// 放行静态资源
.antMatchers("/css/**", "/js/**", "/images/**").permitAll()
// 其他所有请求需要认证
.anyRequest().authenticated()
.and()
// 启用默认登录页
.formLogin();
}
}最佳实践
- 路径匹配:使用
antMatchers()匹配静态资源目录(如/resources/**) - 常见静态路径:
/css,/js,/images,/webjars - 顺序原则:先声明
permitAll()再声明authenticated() - 禁用CSRF:对静态资源可添加
.csrf().ignoringAntMatchers("/static/**")
常见错误
- 路径错误:实际资源路径与配置不匹配(如忘记添加
/**) - 顺序错误:将
anyRequest().authenticated()放在permitAll()之前导致规则覆盖 - 遗漏登录配置:未启用
formLogin()导致无认证入口 - 缓存问题:浏览器缓存旧安全策略,需强制刷新(Ctrl+F5)
扩展知识
- 自定义登录页:通过
.formLogin().loginPage("/custom-login")指定 - 内存认证:重写
configure(AuthenticationManagerBuilder auth)可添加测试用户:auth.inMemoryAuthentication() .withUser("user").password("{noop}pass").roles("USER"); - 新版适配:Spring Security 5.7+ 推荐使用组件式配置(无需继承 WebSecurityConfigurerAdapter):
@Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeRequests(auth -> auth .antMatchers("/static/**").permitAll() .anyRequest().authenticated() ); return http.build(); }