Spring Security - Lambda DSL

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

Lambda DSL 總覽

Spring Security 5.2 的發佈版本包含了 DSL 的增強功能,允許使用 Lambda 運算式配置 HTTP 安全性。

務必注意,先前的配置樣式仍然有效且受支援。新增 Lambda 運算式旨在提供更大的彈性,但它們的使用是選用的。

您可能在 Spring Security 文件範例中看過這種配置樣式。讓我們看看 HTTP 安全性的 Lambda 配置與先前的配置樣式相比如何。

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

您也可以使用類似的方式,使用 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 社群中所有即將到來的活動。

檢視全部