web-dev-qa-db-ja.com

Spring Securityで複数のHTTPセクションを作成するJava Config

Spring Security XML構成を使用すると、複数のHTTP要素を定義して、アプリケーションのさまざまな部分にさまざまなアクセスルールを指定できます。 8.6 Advanced Namespace Configuration の例は、アプリケーションのステートフルセクションとステートレスセクションを個別に定義します。前者はセッションとフォームログインを使用し、後者はセッションなしとBASIC認証を使用します。

_<!-- Stateless RESTful service using Basic authentication -->
<http pattern="/restful/**" create-session="stateless">
    <intercept-url pattern='/**' access='ROLE_REMOTE' />
    <http-basic />
</http>

<!-- Empty filter chain for the login page -->
<http pattern="/login.htm*" security="none"/>

<!-- Additional filter chain for normal users, matching all other requests -->
<http>
    <intercept-url pattern='/**' access='ROLE_USER' />
    <form-login login-page='/login.htm' default-target-url="/home.htm"/>
    <logout />
</http>
_

Java Config。で同じことを行う方法がわかりません。セッションを無効にし、Webサービスに別のエントリポイントを使用することが重要です。現在、次のものがあります。

_@Override
public void configure(WebSecurity security)
{
    security.ignoring().antMatchers("/resource/**", "/favicon.ico");
}

@Override
protected void configure(HttpSecurity security) throws Exception
{
    security
            .authorizeRequests()
                .anyRequest().authenticated()
            .and().formLogin()
                .loginPage("/login").failureUrl("/login?loginFailed")
                .defaultSuccessUrl("/ticket/list")
                .usernameParameter("username")
                .passwordParameter("password")
                .permitAll()
            .and().logout()
                .logoutUrl("/logout").logoutSuccessUrl("/login?loggedOut")
                .invalidateHttpSession(true).deleteCookies("JSESSIONID")
                .permitAll()
            .and().sessionManagement()
                .sessionFixation().changeSessionId()
                .maximumSessions(1).maxSessionsPreventsLogin(true)
                .sessionRegistry(this.sessionRegistryImpl())
            .and().and().csrf()
                .requireCsrfProtectionMatcher((r) -> {
                    String m = r.getMethod();
                    return !r.getServletPath().startsWith("/services/") &&
                            ("POST".equals(m) || "PUT".equals(m) ||
                                    "DELETE".equals(m) || "PATCH".equals(m));
                });
}
_

これを使用して、WebサービスのCSRF保護を無効にすることができました。しかし、セッションを無効にして別のエントリポイントを指定するには、まったく別のHTTP構成が本当に必要です。 requestMatcherまたはrequestMatchersを使用して適用するURIを制限できることは知っていますが、これを使用して個別の構成を作成できるようには見えません。それは私が必要とするようなものですtwoconfigure(HttpSecurity security)メソッド。

26
Nick Williams

Spring Securityでは、XMLの複数の<http>要素の動作をJava configでセキュリティ構成用に複数のクラスを作成します。一般的には、共通のセキュリティ構成を作成するのが最良/最も簡単です。 HttpSecurityのセキュリティ定義に複数の内部クラスを使用します。サンプルについては here を参照してください。

また、Spring Securityの公式ドキュメントの関連セクション:
5.7複数のHttpSecurity

28
M. Deinum