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 社群所有即將舉行的活動。

檢視所有