Java 后端面试题库 / 全部题解免费阅读理解原理,有条理地回答

如何配置 Spring Security 保护 URL?

查看完整题解

参考回答

直接回答

定义一个 SecurityFilterChain Bean,在 authorizeHttpRequests 中从具体路径写到兜底规则。下面的 Servlet 示例允许匿名访问 /public,只有管理员能进入 /admin/**,其他请求都需要登录。

讲清原理

requestMatchers 选链内的授权规则,securityMatcher 才决定这条链是否处理某个请求。示例依赖 Spring Security 7.1.2 的 Web 与 Config 模块,并运行在启用了 Web Security、已经提供用户认证数据的应用中。

例子与易错点

把以下 Bean 方法放进安全配置类。表单登录使用框架默认入口。

@Bean
SecurityFilterChain siteSecurity(HttpSecurity http) throws Exception {
    return http
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/public").permitAll()
            .requestMatchers("/admin/**").hasRole("ADMIN")
            .anyRequest().authenticated())
        .formLogin(Customizer.withDefaults())
        .build();
}

Bean 来自 org.springframework.context.annotation,HttpSecurity 来自 org.springframework.security.config.annotation.web.builders,Customizer 来自 org.springframework.security.config,SecurityFilterChain 来自 org.springframework.security.web。可用匿名访问和普通用户访问两组请求检查登录跳转与拒绝结果。

相关题:第 22 题、第 31 题。

这道题,你掌握得怎么样?

掌握程度由你主动标记,阅读和收藏不会自动改变状态。