Java 如何允许/api/**;通过我的基本身份验证配置,并在Spring Security中进入我的oauth配置

Java 如何允许/api/**;通过我的基本身份验证配置,并在Spring Security中进入我的oauth配置,java,spring-security,oauth-2.0,basic-authentication,Java,Spring Security,Oauth 2.0,Basic Authentication,我有一个应用程序,同时使用基本身份验证和OAuth2 一些URL使用基本身份验证进行授权,而“/api/**”使用OAuth2进行授权 目前,我有两个Java配置文件(WebSecurityConfigureAdapter和ResourceServerConfigurerAdapter) 每个配置文件都定义了一个public void configure(HttpSecurity http)方法 我遇到的问题是,在给定url请求的情况下,我需要一种优雅的方式来告诉我的应用程序是使用basic a

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

一些URL使用基本身份验证进行授权,而“/api/**”使用OAuth2进行授权

目前,我有两个Java配置文件(
WebSecurityConfigureAdapter
ResourceServerConfigurerAdapter

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

我遇到的问题是,在给定url请求的情况下,我需要一种优雅的方式来告诉我的应用程序是使用basic auth还是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)
,但由于它实际上不返回匹配项,只返回“find==true”,因此似乎无法完成任务

有什么想法/建议吗?

您可以使用:

将否定传入的请求匹配器的请求匹配器。例如,如果传入的RequestMatcher返回true,则NegateRequestMatcher将返回false。如果传入的RequestMatcher返回false,则NegateRequestMatcher将返回true

您应该在
@Configuration
类上使用
Order(…)
注释。首先将您的
OAuth2ServerConfig
config设置为只提供
http.requestMatchers().antMatchers(“/api/**”)服务,然后将
WebSecurityConfig设置为第二(
@Order(2)
),而不提供
http.requestMatchers()
服务所有剩余URL

详见