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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18815015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:18:32  来源:igfitidea点击:

Creating multiple HTTP sections in Spring Security Java Config

javaspring-securityconfig

提问by Nick Williams

Using Spring Security XML configuration, you can define multiple HTTP elements to specify different access rules for different parts of your application. The example given in 8.6 Advanced Namespace Configurationdefines separate stateful and stateless sections of the application, with the former using sessions and form login, and the latter using no sessions and BASIC authentication:

使用 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>

I can't figure out how to do the same thing with Java Config. It's important that I disable sessions and use a different entry point for my web services. Right now I have the following:

我不知道如何用 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));
                });
}

Using this I was able to disable CSRF protection for my web services. But I really need a whole separate HTTP configuration so that I can disable sessions and specify a different entry point. I know I can use requestMatcheror requestMatchersto restrict the URIs that it applies to, but it doesn't appear that you can use this to create separate configurations. It's almost like I need twoconfigure(HttpSecurity security)methods.

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

采纳答案by M. Deinum

In Spring Security to mimic the behavior of multiple <http>elements from XML in Java config create multiple classes for security configuration. In general it is the best/easiest to create a common security configuration with multiple inner classesfor the security definition for HttpSecurity. See herefor a sample.

在 Spring Security 中模仿<http>Java 配置中 XML 中多个元素的行为,为安全配置创建多个类。通常它是最好的/最容易制作具有共同的安全配置的多个内部类用于安全定义HttpSecurity。请参阅此处获取示例。

And here the related section in the official Spring Security documentation:
5.7 Multiple HttpSecurity

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