为什么 Spring Security permitAll 不起作用?

Why is Spring Security permitAll not working?

这是我的配置。我希望任何包含 ADMIN 的 URL 部分只能由管理员访问,其他所有内容 - 免费使用。但它会为未登录的用户提供“错误”:“未经授权”。

    @Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .csrf().disable()
            .httpBasic()
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .headers().frameOptions().disable()
            .and()
            .authorizeRequests()
            .antMatchers("**/admin/**").hasRole(Role.ADMIN.getAuthority())
            .anyRequest().permitAll();
}

Copy/pasted 您在新项目中的配置,只需进行一次修改即可按预期工作,更确切地说,将 .antMatchers 替换为 .mvcMatchers

使用 .antMatchers 而不是 .mvcMatchers 是一个常见的陷阱,因为它有时会产生意想不到的结果。例如,在我的 Spring 版本中,您的 .antMatchers("**/admin/**") 不匹配 /s2/admin/s2,因为匹配器不以 / 开头。此匹配在 Spring 的 AntPathMatcher.class 中失败。

通过使用 .mvcMatchers,您可以使用与控制器相同的网络路径解析器。