【Spring Security】如何使用Lambda DSL配置Spring Security
创始人
2024-05-15 13:24:33
0

本期目录

  • 1. 概述
  • 2. 新老配置风格对比
    • Lambda风格
    • 等效的旧配置风格
  • 3. WebFlux Security
  • 4. Lambda DSL的目标



1. 概述

在 Spring Security 5.2 中增强了 DSL 的功能:允许使用 Lambda 表达式来配置 HTTP security 。

需要注意的是:先前版本的配置风格仍然是有效的且受支持的。Spring 官方额外新增 Lambda 表达式是为了提高代码的灵活性,只是一个可选的用法。

下面让我们看一下 Lambda 表达式配置 HTTP security 和先前的配置风格的对比。


2. 新老配置风格对比


Lambda风格

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests(authorizeRequests ->authorizeRequests.antMatchers("/blog/**").permitAll().anyRequest().authenticated()).formLogin(formLogin ->formLogin.loginPage("/login").permitAll()).rememberMe(withDefaults());}
}

等效的旧配置风格

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/blog/**").permitAll().anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().rememberMe();}
}

对比上述两种配置风格,你会注意到一些关键的不同点:

  • 在 Lambda 风格中,不再需要通过 .and() 方法来串联配置项。

    在调用 Lambda 方法后,HttpSecurity 对象 http 会自动返回以继续执行进一步的配置。

  • 方法 withDefaults() 可以使用 Spring Security 提供的默认值启用安全功能。这是 Lambda 表达式 it -> {} 的快捷方式。


3. WebFlux Security

此外,你还可以使用 Lambda 表达式来配置 WebFlux security ,配置方式与上面基本相似。

举个例子:

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

4. Lambda DSL的目标

Lambda DSL 被开发出来,是为了完成以下的目的:

  • 自动缩进以提高配置的可读性。
  • 不再需要使用 .and() 方法来串联配置项。
  • Spring Security DSL 与其他 Spring DSLs (例如 Spring Integration 和 Spring Cloud Gateway ) 拥有相似的配置风格。

相关内容

热门资讯

监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
在Word、WPS中插入AxM... 引言 我最近需要写一些文章,在排版时发现AxMath插入的公式竟然会导致行间距异常&#...
【PdgCntEditor】解... 一、问题背景 大部分的图书对应的PDF,目录中的页码并非PDF中直接索引的页码...
Fluent中创建监测点 1 概述某些仿真问题,需要创建监测点,用于获取空间定点的数据࿰...
educoder数据结构与算法...                                                   ...
MySQL下载和安装(Wind... 前言:刚换了一台电脑,里面所有东西都需要重新配置,习惯了所...
修复 爱普生 EPSON L4... L4151 L4153 L4156 L4158 L4163 L4165 L4166 L4168 L4...
MFC文件操作  MFC提供了一个文件操作的基类CFile,这个类提供了一个没有缓存的二进制格式的磁盘...