2017-02-08 7 views
0

私はBasic AuthとOAuth2の両方を使用するアプリケーションを持っています。私の基本的なauth設定と春のセキュリティのoauth設定に "/ api/**"を許可する方法

一部のURLはBasic Authを使用して承認され、「/ api/**」はOAuth2を使用して承認されます。

現在、私は2つのJavaの設定ファイル(WebSecurityConfigurerAdapterResourceServerConfigurerAdapter

設定ファイルの各がpublic void configure(HttpSecurity http)メソッドを定義しています。

私が抱えている問題は、私のアプリケーションに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)しかし、実際には一致を返さず、 "find == true"を返すだけなので、ジョブが完了していないようです。

ご意見/ご提案はありますか?

答えて

2

あなたはNegatedRequestMatcherを使用することができます。

RequestMatcherを否定しますRequestMatcherが渡さ例えば、RequestMatcherがtrueを返すに渡された場合、NegatedRequestMatcherはfalseを返します。渡されたRequestMatcherがfalseを返す場合、NegatedRequestMatcherはtrueを返します。

0

@ConfigurationクラスでOrder(...)アノテーションを使用する必要があります。 OAuth2ServerConfigを最初に設定し、http.requestMatchers().antMatchers("/api/**")にのみサービスし、http.requestMatchers()を使わないでWebSecurityConfig@Order(2))を残りのすべてのURLに配信するようにしてください。

詳細を参照してください。https://stackoverflow.com/a/44871933/173149

関連する問題