28

使用 Spring Security XML 配置,您可以定义多个 HTTP 元素来为应用程序的不同部分指定不同的访问规则。8.6 高级命名空间配置中给出的示例定义了应用程序的单独的有状态和无状态部分,前者使用会话和表单登录,后者使用无会话和 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 配置,以便我可以禁用会话并指定不同的入口点。我知道我可以使用requestMatcherrequestMatchers限制它适用的 URI,但您似乎不能使用它来创建单独的配置。这几乎就像我需要两种 configure(HttpSecurity security)方法。

4

1 回答 1

34

在 Spring Security 中,为了模仿<http>Java 配置中 XML 中的多个元素的行为,为安全配置创建多个类。一般来说,HttpSecurity. 请参阅此处获取示例。

这里是官方 Spring Security 文档中的相关部分:
5.7 Multiple HttpSecurity

于 2013-09-18T05:51:39.707 回答