【问题标题】:Spring Security - permit only requests with prefixSpring Security - 只允许带有前缀的请求
【发布时间】:2020-06-10 16:13:07
【问题描述】:

除了以/unsecured 开头的端点外,我需要保护资源服务器中的所有其余端点。因此,应该允许所有人提出以下请求:

  • /unsecured/foo/bar
  • /unsecured
  • ...

但是这样的请求:

  • /foo/unsecured/bar
  • /foo/bar
  • ...

应该需要身份验证。

@Configuration
@EnableResourceServer
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity security) throws Exception {
        security
            .authorizeRequests(authorizeRequests -> {
                authorizeRequests.antMatchers("unsecured/**").permitAll();
                authorizeRequests.anyRequest().authenticated();
            });
    }
}

但在上面的配置中,所有端点都需要身份验证。

这是我尝试访问不安全端点时收到的响应:

代码 401

{
    "error": "unauthorized",
    "error_description": "Full authentication is required to access this resource"
}

【问题讨论】:

  • 你不想authorizeRequests.antMatchers("unsecured/**").permitAll();
  • @AlanHay 是的,很抱歉,我只是抄错了我的代码。谢谢。

标签: spring-boot spring-mvc spring-security spring-security-oauth2


【解决方案1】:

premitAll() 是您正在寻找的。看起来您只是缺少 URL 之前的 /

@Configuration
@EnableResourceServer
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity security) throws Exception {
        security
            .authorizeRequests(authorizeRequests - > {
                authorizeRequests.antMatchers("/unsecured/**").permitAll();
                authorizeRequests.anyRequest().authenticated();
            });
    }
}

【讨论】:

  • 真的很抱歉。我不好复制我的代码。我已经在第一行有 permitAll()。
  • 也许您需要在不安全之前使用“/”?
  • 是的,它有效,但很奇怪。谢谢你。您可以更新答案,我会将其标记为答案
猜你喜欢
  • 2016-01-31
  • 2015-10-04
  • 1970-01-01
  • 2019-03-07
  • 2022-11-10
  • 2021-01-04
  • 1970-01-01
  • 2018-08-19
  • 2017-05-10
相关资源
最近更新 更多