Spring Security - Lambda DSL

工程 | Eleftheria Stein-Kousathana | 2019年11月21日 | ...

Lambda DSL 概述

Spring Security 5.2 的发布包括了对 DSL 的增强,允许使用 Lambda 配置 HTTP 安全性。

需要注意的是,之前的配置风格仍然有效并受支持。Lambda 的添加旨在提供更大的灵活性,但其使用是可选的。

您可能在 Spring Security 的文档示例中见过这种配置风格。让我们来看看使用 Lambda 配置 HTTP 安全性与之前的配置风格有何不同。

使用 Lambda 的配置

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests(authorizeRequests ->
                authorizeRequests
                    .antMatchers("/blog/**").permitAll()
                    .anyRequest().authenticated()
            )
            .formLogin(formLogin ->
                formLogin
                    .loginPage("/login")
                    .permitAll()
            )
            .rememberMe(withDefaults());
    }
}

不使用 Lambda 的等效配置

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/blog/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .rememberMe();
    }
}

Lambda DSL 配置技巧

比较上述两个示例,您会注意到一些关键区别

  • 在 Lambda DSL 中,无需使用 .and() 方法来链式配置选项。在调用 Lambda 方法后,HttpSecurity 实例会自动返回以进行进一步配置。
  • withDefaults() 使用 Spring Security 提供的默认值启用安全功能。这是 Lambda 表达式 it -> {} 的快捷方式。

WebFlux 安全性

您也可以以类似的方式使用 Lambda 配置 WebFlux 安全性。下面是一个使用 Lambda 的配置示例。

@EnableWebFluxSecurity
public class SecurityConfig {

    @Bean
    SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        http
            .authorizeExchange(exchanges ->
                exchanges
                    .pathMatchers("/blog/**").permitAll()
                    .anyExchange().authenticated()
            )
            .httpBasic(withDefaults())
            .formLogin(formLogin ->
                formLogin
                    .loginPage("/login")
            );
        return http.build();
    }
}

Lambda DSL 的目标

Lambda DSL 的创建旨在实现以下目标

  • 自动缩进使配置更具可读性。
  • 无需使用 .and() 链式连接配置选项。
  • Spring Security DSL 具有与其他 Spring DSL(如 Spring Integration 和 Spring Cloud Gateway)相似的配置风格。

获取 Spring 新闻通讯

通过 Spring 新闻通讯保持联系

订阅

领先一步

VMware 提供培训和认证,助您加速进步。

了解更多

获得支持

Tanzu Spring 提供 OpenJDK™、Spring 和 Apache Tomcat® 的支持和二进制文件,只需一份简单的订阅。

了解更多

即将举行的活动

查看 Spring 社区所有即将举行的活动。

查看所有