如何通过我的基本身份validation配置允许“/ api / **”并进入我在Spring Security中的oauth配置

我有一个使用Basic Auth和OAuth2的应用程序。

某些URL使用Basic Auth授权,“/ api / **”使用OAuth2授权。

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

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

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

目前我正在使用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。

您应该在@Configuration类上使用Order(...)注释。 首先制作你的OAuth2ServerConfig配置并仅提供http.requestMatchers().antMatchers("/api/**")并使你的WebSecurityConfig第二个( @Order(2) )没有http.requestMatchers()来提供所有其余的URL!

有关https://stackoverflow.com/a/44871933/173149的详细信息,请参阅