在Spring Security Java Config中创建多个HTTP部分

Nic*_*ams 26 java config spring-security

使用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>
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚如何使用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));
                });
}
Run Code Online (Sandbox Code Playgroud)

使用此功能,我可以为我的Web服务禁用CSRF保护.但我真的需要一个完整的单独HTTP配置,以便我可以禁用会话并指定不同的入口点.我知道我可以使用requestMatcherrequestMatchers限制它适用的URI,但似乎不能使用它来创建单独的配置.这几乎就像我需要两种 configure(HttpSecurity security)方法.

M. *_*num 28

在Spring Security中,<http>在Java配置中模仿XML中多个元素的行为,为安全配置创建多个类.通常,为安全性定义创建具有多个内部类的公共安全性配置是最好/最简单的HttpSecurity.请看这里的样本.

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

  • 这个答案的关键是每个安全配置类必须在第一个 antMatcher() 中标识一个唯一的 URL 路径。如:`protected void configure(HttpSecurity http) { http.antMatcher("/secure**")` 旁边:`protected void configure(HttpSecurity http) { http.antMatcher("/api/**")` 问题问题中的代码是此代码匹配所有网址:`security.authorizeRequests()` (5认同)