2017-06-01 26 views
1

私のSpring Bootプロジェクトでは、特定のIPアドレスを持つ複数の管理者ユーザにアクセスしようとしています。Springのセキュリティ設定で単一の役割の複数のIPアドレス

複数のIPアドレスに1つの役割を割り当てることはできますか。

私のセキュリティ設定のコードは動作しませんでした。私の要求の

@SuppressWarnings("ALL") 
@Configuration 
@EnableWebSecurity 
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     List<String> ipAddresses = new ArrayList<>(); 
     ipAddresses.add("127.0.0.1"); 
     ipAddresses.add("192.168.1.0/24"); 
     ipAddresses.add("0:0:0:0:0:0:0:1"); 

     for (String ip : ipAddresses) { 
      http.authorizeRequests(). 
        antMatchers("/admin" + "/**") 
        .access("hasRole('admin') and hasIpAddress('" + ip + "')"); 
     } 
    } 

    //some other configurations 
} 

URLを(私は簡単にするためにハードコードされたロール名とIPアドレスを与えています):次のような構成でhttp://localhost:9595/admin/checkappeals/211

+1

は、私は次のエラーを取得していますが指定されたリソースは禁止されています。 – user7244716

答えて

2

あなたforループ結果:

@SuppressWarnings("ALL") 
@Configuration 
@EnableWebSecurity 
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 

     http 
      .authorizeRequests() 
       .antMatchers("/admin/**").access("hasRole('admin') and hasIpAddress('127.0.0.1')") 
       .antMatchers("/admin/**").access("hasRole('admin') and hasIpAddress('192.168.1.0/24')") 
       .antMatchers("/admin/**").access("hasRole('admin') and hasIpAddress('0:0:0:0:0:0:0:1')"); 
    } 

    //some other configurations 
} 

したがって、URL:

http://localhost:9595/admin/checkappeals/211 

のみ最初のマッチャーが考慮され、HttpSecurity#authorizeRequests次を参照してください。

Note that the matchers are considered in order. Therefore, the following is invalid because the first matcher matches every request and will never get to the second mapping:

http.authorizeRequests().antMatchers("/**").hasRole("USER").antMatchers("/admin/**") 
      .hasRole("ADMIN") 

をあなたが何か構築する必要があります:HTTPステータス403回の-message-説明アクセスへ:

http 
    .authorizeRequests() 
     .antMatchers("/admin/**").acces("hasRole('admin') and (hasIpAddress('127.0.0.1') or hasIpAddress('192.168.1.0/24') or hasIpAddress('0:0:0:0:0:0:0:1'))"; 
+0

私は同じ問題を抱えています。あなたはこれをリストとして機能させる方法を知っていますか?私の問題は、各IPがアクセスパラメータ内にある解決法が機能しないように、(設定ファイルから読み込まれる)認可する必要のある未知数のIPアドレスがあることです。ありがとう – haddow64

+2

@ haddow64:StringBuilder(または類似のもの)を使用し、forループの条件をconcatinateします。完全な条件は 'antMatchers("/admin/** ")。access(condition)'のように使います。 – dur

関連する問題