如何将 web.xml 中的 <security-constraint> 迁移到基于 spring class 的配置 (WebApplicationInitializer)

How to migrate <security-constraint> in web.xml to spring class based configuration (WebApplicationInitializer)

在我们当前基于 XML 的配置中,我们在 web.xml 中进行了以下配置以禁用非 ssl(HTTP) 协议访问。

<security-constraint>
    <web-resource-collection>
        <web-resource-name>SecureConnection</web-resource-name>
        <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint>


我正在将这个基于 XML 的配置迁移到 Java 配置。如何在 Spring WebApplicationInitializer 中设置此配置。我找到了@ams 多年前发布的 same question,但没有 complete/proper 答案。我如何使用 Java 配置实现此目的。

您创建了一个WebSecurityConfigurerAdapter and configure the HttpSecurity

您应该阅读 HttpSecurity 的文档以找出您需要应用的正确配置。

基本示例:

 @Configuration
 @EnableWebSecurity
 public class OpenIDLoginConfig extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) {
                http.authorizeRequests().antMatchers("/**").hasRole("USER").and().openidLogin()
                                .permitAll();
        }

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
                auth.inMemoryAuthentication()
                                .withUser("https://www.google.com/accounts/o8/id?id=lmkCn9xzPdsxVwG")
                                .password("password").roles("USER");
        }
 }

进一步阅读:https://www.baeldung.com/java-config-spring-security

我发现以下解决方案仅通过 SSL(HTTPS) 访问请求并在通过 Spring HttpSecurity class。对此进行了测试并且工作正常。需要配置 WebSecurityConfigurerAdapter

的重写 configure() 方法
http.requiresChannel().anyRequest().requiresSecure();