2013-09-10 10 views
7

私は、異なるURLパターンに対して2つの異なるセキュリティ設定を定義しようとしています。その1つはフォームログインを使用し、もう1つは基本認証を使用します。Springセキュリティによる基本認証とフォームベースの認証Javaconfig

私が探している解決策は、http://meera-subbarao.blogspot.co.uk/2010/11/spring-security-combining-basic-and.htmlで説明したものと似ていますが、私はjavaの設定を使ってやりたいと思います。

ありがとうございます。

これは私が現在持っている設定です。

@Configuration 
@EnableWebSecurity 
public class AppSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Autowired 
    private UserService userService; 

    @Override 
    protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception { 
     auth.userDetailsService(userService); 
    } 

    @Override 
    public void configure(WebSecurity web) throws Exception { 
     // Ignore any request that starts with "/resources/". 
     web.ignoring().antMatchers("/resources/**"); 
    } 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http.authorizeUrls().antMatchers("/", "/index", "/user/**", "/about").permitAll() 
     .antMatchers("/admin/**").hasRole("ADMIN") 
     .anyRequest().authenticated() 
     .and().formLogin() 
     .loginUrl("/login") 
     .failureUrl("/login-error") 
     .loginProcessingUrl("/security_check") 
     .usernameParameter("j_username").passwordParameter("j_password") 
     .permitAll(); 

     http.logout().logoutUrl("/logout"); 
     http.rememberMe().rememberMeServices(rememberMeServices()).key("password"); 
    } 

    @Bean 
    public RememberMeServices rememberMeServices() { 
     TokenBasedRememberMeServices rememberMeServices = new TokenBasedRememberMeServices("password", userService); 
     rememberMeServices.setCookieName("cookieName"); 
     rememberMeServices.setParameter("rememberMe"); 
     return rememberMeServices; 
    } 
} 
+0

どのような結果が表示されますか? – Taylor

+0

現在、私はちょうどこのフォーム認証を持っており、/ api/*のようなURLパターンに基本認証を追加する方法を見つけることができません –

答えて

9

ソリューションは、最初の1の内側WebSecurityConfigurerAdapterを拡張する別のクラスを作成することでした、説明されるように、次のようにhttps://github.com/spring-projects/spring-security-javaconfig/blob/master/samples-web.md#sample-multi-http-web-configuration

私のソリューションは、次のとおりです。

@Configuration 
@EnableWebSecurity 
public class AppSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Autowired 
    private UserService userService; 

    @Override 
    protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception { 
     auth.userDetailsService(userService); 
    } 

    @Override 
    public void configure(WebSecurity web) throws Exception { 
     // Ignore any request that starts with "/resources/". 
     web.ignoring().antMatchers("/resources/**"); 
    } 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http.authorizeUrls().antMatchers("/", "/index", "/user/**", "/about").permitAll() 
      .antMatchers("/admin/**").hasRole("ADMIN") 
      .anyRequest().authenticated() 
      .and().formLogin() 
      .loginUrl("/login") 
      .failureUrl("/login-error") 
      .loginProcessingUrl("/security_check") 
      .usernameParameter("j_username").passwordParameter("j_password") 
      .permitAll(); 

     http.logout().logoutUrl("/logout"); 
     http.rememberMe().rememberMeServices(rememberMeServices()).key("password"); 
    } 

    @Bean 
    public RememberMeServices rememberMeServices() { 
     TokenBasedRememberMeServices rememberMeServices = new TokenBasedRememberMeServices("password", userService); 
     rememberMeServices.setCookieName("cookieName"); 
     rememberMeServices.setParameter("rememberMe"); 
     return rememberMeServices; 
    } 

    @Configuration 
    @Order(1) 
    public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter { 

     @Override 
     protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception { 
      auth.inMemoryAuthentication().withUser("api").password("pass").roles("API"); 
     } 

     protected void configure(HttpSecurity http) throws Exception { 
      http.authorizeUrls() 
       .antMatchers("/api/**").hasRole("API") 
       .and() 
       .httpBasic(); 
     } 
    } 
} 
2

私は単にそれをすることによって言うでしょう。 authorizeUrls()で2行目を指定しますが、基本認証に必要なURLには2行目を指定します。代わりにformLogin()使用のようなものが動作するはずhttpBasic()

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http.authorizeUrls().antMatchers("/", "/index", "/user/**", "/about").permitAll() 
    .antMatchers("/admin/**").hasRole("ADMIN") 
    .anyRequest().authenticated() 
    .and().formLogin() 
    .loginUrl("/login") 
    .failureUrl("/login-error") 
    .loginProcessingUrl("/security_check") 
    .usernameParameter("j_username").passwordParameter("j_password") 
    .permitAll(); 

    http.authorizeUrls().antMatchers("/api/*").hasRole("YOUR_ROLE_HERE").and().httpBasic(); 

    http.logout().logoutUrl("/logout"); 
    http.rememberMe().rememberMeServices(rememberMeServices()).key("password"); 
} 

の。

リンク:HttpSecurity,。私が見つけた

+0

apiはauthorizeUrls()を呼び出すと前の呼び出しを上書きするそれはおそらくこのようにすることはできません –

0

あなただけの後.antMatcher("/api/**")を追加することによって、それを解決することができますあなたの最初の設定のhttp/apiのURLだけを管理します。あなたは最初のアダプタでそれを持っている必要があります。

http 
    .antMatcher("/api/*") 
    .authorizeRequests() 
     .antMatchers("^/api/.+$").hasRole("ADMIN") 
    .... 
-1

ここで他の回答が比較的古いされており、例えば、私はSpringBoot 1.4.0 /春の4春4のauthorizeUrls

を見つけることができません、私はこのような基本的な/フォーム・ログイン実装しました:

@EnableWebSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter 
{ 
    protected void configure (HttpSecurity aHttp) throws Exception 
    {  
     aHttp.authorizeRequests().antMatchers (("/api/**")).fullyAuthenticated().and().httpBasic(); 

     aHttp.formLogin() 
     .loginPage ("/login").permitAll() 
     .and().logout().permitAll(); 
    } 
} 

これを書いているよりellegant方法があるかもしれません - 私はまだ、このビルダーは、などのシーケンスの観点で動作し、どのように理解することに取り組んでいます。しかし、これはうまくいった。

+0

これは私のために動作しません -/apiへのアクセス/は、基本認証ではなくログインフォームにリダイレクトされます。 –

+0

@JamesBaker - OPは基本認証のためにPRする必要があるとは言及していませんでしたが、基本認証は上で動作します。あなたのソートのHTTPクライアントを使用し、あなたの要求で基本認証の信用を送信する場合、それは動作します。 – ETL

0

明らかに、春の更新として、これらは適用性が衰える傾向があります。ランニング春のクラウドスターターセキュリティ1.4.0.RELEASEこれは私のソリューションです。クラウド構成の基本認証を使用してリフレッシュ・エンドポイントを保護し、他のすべてのインスタンスで認証を渡すためにスプリング・セッションを持つゲートウェイを使用しているため、私のユース・ケースは少し異なりました。

@EnableWebSecurity 
@Configuration 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 

    @Autowired 
    public void configureGlobal1(AuthenticationManagerBuilder auth) throws Exception { 
     //try in memory auth with no users to support the case that this will allow for users that are logged in to go anywhere 
     auth.inMemoryAuthentication(); 
    } 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
      .httpBasic() 
       .disable() 
      .authorizeRequests() 
       .antMatchers(HttpMethod.POST, "/user").permitAll() 
       .anyRequest().authenticated() 
       .and() 
      .csrf().disable(); 
    } 

    @Bean 
    public BCryptPasswordEncoder encoder() { 
     return new BCryptPasswordEncoder(11); 
    } 

    @Configuration 
    @Order(1) 
    public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter { 

     @Autowired 
     private AuthenticationProvider customAuthenticationProvider; 

     @Autowired 
     protected void configureGlobal2(AuthenticationManagerBuilder auth) throws Exception { 
      auth 
        .authenticationProvider(customAuthenticationProvider); 
     } 

     @Override 
     protected void configure(HttpSecurity http) throws Exception { 
      http 
       .httpBasic() 
        .and() 
       .authorizeRequests() 
        .antMatchers(HttpMethod.POST, "/refresh").hasRole("SUPER") 
        .and() 
       .csrf().disable(); 
     } 
    } 
} 

さらに明確化のために春のセキュリティのドキュメントを参照してください。Spring Security

基本的な考え方は、@Orderアノテーションは認証スキームが実行される順序何をするか決めていることです。 @Orderは、それが最後であることを意味しません。 authorizeRequests()セクションが受信URLで一致しない場合、その設定は合格し、次のものは認証を試みます。これは、認証が成功するか失敗するまで続行されます。

関連する問題