我有一个同时使用基本身份验证和OAuth2的应用程序。

某些网址是使用基本身份验证授权的,“ / api / **”是使用OAuth2授权的。

当前,我有两个Java配置文件(WebSecurityConfigurerAdapterResourceServerConfigurerAdapter

每个配置文件都定义一个public void configure(HttpSecurity http)方法。

我遇到的麻烦是,我需要一种优雅的方法来告诉我的应用程序是否使用基本auth或给定url请求的oauth2。

目前,我正在使用requestMatchers来实现此目的:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{
  @Override
  protected void configure(HttpSecurity http) throws Exception
  {
    http
      .csrf().disable()
    .requestMatchers()
      .antMatchers("/*", "/login/**", "/reviews/**")
    .and()
    .authorizeRequests()
      .antMatchers("/*").permitAll()
      .antMatchers("/js/**").permitAll()
      .antMatchers("/img/**").permitAll()
    .formLogin()
      .loginPage("/login")
      .successHandler(loginSuccessPostHandler)
      .permitAll()
      .and()
    .logout()
      .logoutSuccessUrl("/").permitAll()
      .and()
    .apply(getSpringSocialConfigurer());
  }
}

@Configuration
public class OAuth2ServerConfig
{
  @Configuration
  @EnableResourceServer
  protected static class Oauth2ServerConfig extends ResourceServerConfigurerAdapter
  {
    @Override
    public void configure(HttpSecurity http) throws Exception
    {
      http.httpBasic().disable();
      http.csrf().disable();

      http.requestMatchers()
        .antMatchers("/api/**")
        .and()
      .authorizeRequests()
        .antMatchers("/api/v1/**").access("#oauth2.hasScope('read')");
    }
  }
}


问题是,每当我添加一个不是“ / api / **”的新URL时,都需要将其添加到我的WebSecurityConfig的requestMatcher部分中……这可能会在将来导致愚蠢的错误。

有没有一种方法可以基于负前瞻正则表达式进行requestMatcher搜索?我使用正则表达式进行了尝试:^(?!/api),但是由于它实际上并未返回MATCH,而仅返回了“ find == true”,因此似乎无法完成工作。

有什么想法/建议吗?

最佳答案

您可以使用NegatedRequestMatcher


  一个将使传入的RequestMatcher无效的RequestMatcher。例如,如果传入的RequestMatcher返回true,则NegatedRequestMatcher将返回false。如果传入的RequestMatcher返回false,则NegatedRequestMatcher将返回true。

07-27 17:19