Spring 安全 - 只允许带有前缀的请求

Spring Security - permit only requests with prefix

除了以 /unsecured 开头的端点外,我需要保护资源服务器中的所有其余端点。所以像下面这样的请求应该被允许给每个人:

但是像这样的请求:

应该需要身份验证。

@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"
}

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();
            });
    }
}