Spring 安全性:如何为某些匹配器启用匿名,但对其余匹配器禁用匿名?

Spring security: How can I enable anonymous for some matchers, but disable that for the rest?

我正在尝试启用对我其余部分的匿名访问 api,但对其余部分禁用它。

我试过配置如下:

@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anonymous().and()
    .antMatchers(SOME_URL).authenticated()
    .and()
    .anoymous().disable()
    .antMatchers(OTHER_URL).authenticated();

}

但是后来发现后面的anonymous().disable会覆盖之前的设置

所以有没有人可以给我一些建议,如何为我的 url 的一部分启用匿名?

非常感谢!!!

您可以定义一个 RequestMatcher,一个用于 public url,另一个用于受保护的 url。然后,覆盖接受 WebSecurity 作为参数的配置方法。在这种方法中,您可以将网络配置为忽略您的 public 网址。

private static final RequestMatcher PUBLIC_URLS = new OrRequestMatcher(
    new AntPathRequestMatcher("/public/**")
  );
private static final RequestMatcher PROTECTED_URLS = new NegatedRequestMatcher(PUBLIC_URLS);

 @Override
  public void configure(final WebSecurity web) {
    web.ignoring().requestMatchers(PUBLIC_URLS);
  }

@Override
  protected void configure(final HttpSecurity http) throws Exception {
    http
      .sessionManagement()
      .sessionCreationPolicy(STATELESS)
      .and()
      .exceptionHandling()
      // this entry point handles when you request a protected page and you are not yet
      // authenticated
      .defaultAuthenticationEntryPointFor(forbiddenEntryPoint(), PROTECTED_URLS)
      .anyRequest()
      .authenticated();
      // and other clauses you would like to add. 
}