8

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

私が探しているソリューションは、ここで説明されているものと似ています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;
    }
}
4

5 に答える 5

12

私が見つけた解決策は、最初のクラスの中に WebSecurityConfigurerAdapter を拡張する別のクラスを作成することでした。 -http-web-構成

私の解決策は次のとおりです。

@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();
        }
    }
}
于 2013-09-11T22:31:17.023 に答える
2

私は単にそれを行うことで言います。authorizeUrls() で 2 行目を指定しますが、基本認証で必要な URL を指定します。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, HttpBasicConfgurer.

于 2013-09-11T07:20:37.340 に答える
0

明らかに、Spring が更新されると、これらは適用性が薄れる傾向があります。spring cloud starter security 1.4.0.RELEASE を実行すると、これが私のソリューションです。クラウド構成の基本認証を使用して更新エンドポイントを保護し、Spring セッションでゲートウェイを使用して他のすべてのインスタンスで認証を渡すため、私の使用例は少し異なりました。

@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 ドキュメントを参照してください: Spring Security

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

于 2016-08-23T06:02:19.883 に答える
-1

ここにある他の回答は比較的古く、たとえば、authorizeUrlsSpring 4 では見つかりません。

SpringBoot 1.4.0 / Spring 4 では、次のような基本/フォーム ログインを実装しました。

@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 ();
   }
}

もっと洗練された書き方があるかもしれません。私はまだ、このビルダーがシーケンスなどの観点からどのように機能するかを理解しようと取り組んでいます。しかし、これはうまくいきました。

于 2016-08-13T14:03:14.503 に答える