【问题标题】:Spring Security returns 401 for unsecured URLSpring Security 为不安全的 URL 返回 401
【发布时间】:2016-10-16 05:28:30
【问题描述】:

在 Spring Boot 1.3.3 应用程序中使用 Spring Security 4.0.3。

该应用程序有两种类型的 HTTP 内容:“API” 一个 REST API 和 “UI” 一个基于 Web 的使用接口(Thymeleaf + Spring Web MVC)。

应用程序的 REST API 的大多数端点都使用 Basic 进行保护,但有些不是并且应该始终可用。

简化后的配置如下:

        // In one method, the security config for the "API"
        httpSecurity
                .antMatcher("/api/**")
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER)
                .and()
                .authorizeRequests()
                .antMatchers("/api/ping").permitAll()
                .antMatchers("/api/**").hasRole("USER")
                .and()
                .httpBasic();

        // In another method, the security config for the "UI"
        httpSecurity
                .authorizeRequests()
                .antMatchers("/ui/", "/ui/index.html", "/ui/css/*", "/ui/js/*", "/ui/img/*").permitAll()
                .antMatchers("/ui/user/**").hasRole("USER")
                .antMatchers("/ui/**").denyAll()
                .and()
                .formLogin().loginPage("/ui/login.html").permitAll().failureUrl("/ui/login.html").defaultSuccessUrl("/ui/user/main.html")
                .and()
                .logout().logoutUrl("/ui/logout").permitAll().logoutSuccessUrl("/ui/login.html")
                .and()
                .httpBasic();

对安全端点的访问按预期工作。

但是当用户提供无效的基本身份验证时,访问诸如“.../api/ping”之类的公共端点会失败并返回 401。当然,当没有提供或提供有效的基本身份验证时,此类端点可以正常工作。

这个来自 Spring Security 的 401 令人惊讶。我们如何实现一个从不为选定端点返回任何 401 或 403 的 Spring Security 配置?

感谢您的宝贵时间。

更新 1:添加了有关“UI”存在和安全配置的信息

【问题讨论】:

  • 你有没有想过这个问题?

标签: spring spring-security


【解决方案1】:

顺序很重要。最具体的规则(路径)优先:

httpSecurity
    .antMatchers("/api/ping").permitAll()
    // and then the rest

这是因为如果有像 antMatcher("/api/**") 这样的匹配,Spring Security 将不会评估以后的规则。

【讨论】:

  • 首先,我更新了问题:添加了有关“UI”的详细信息。那么你的提议很遗憾在这里不起作用,因为最初的“andMatcher('/api/**') 似乎需要确保 Spring Security 配置的两个部分是分开的。
猜你喜欢
  • 2017-01-26
  • 2021-11-18
  • 2018-04-26
  • 2017-04-26
  • 2018-11-06
  • 2020-07-24
  • 2020-10-03
  • 1970-01-01
  • 2021-07-28
相关资源
最近更新 更多