Spring Security Reactive
简介
了解 SpringSecurity 的自动配置默认行为: 所有请求都需要登陆才能访问
- SecurityAutoConfiguration
- 导入了 SecurityFilterChain 组件,这个组件就是默认所有请求都需要登陆才可以访问,和默认登陆页
- 而且 SecurityFilterChain 组件增加了一个条件加载 @ConditionalOnDefaultWebSecurity 即如果自定义了就不会加载这个默认组件
- 而且这个是 Servlet 使用的
- SecurityFilterAutoConfiguration
- ReactiveSecurityAutoConfiguration
- MethodSecurityAspectJAutoProxyRegistrar
认证
认证即指登录行为,默认会对所有请求都需要登录才能访问,包括一些静态资源。
放行静态资源为不需要登录可访问
Security 中提供了一个用于包含所有静态文件的类 PathRequest.toStaticResources().atCommonLocations() 它会包含所有常规的静态资源的路径地址
// 覆盖原有的 SecurityWebFilterChain 过滤器组件配置
@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http){
// 以前的 Servlet 是 authorizeRequest 。因为 Flux 现在的叫法叫 Exchange 包含了 Request 和 Response
http.authorizeExchange(authorize -> {
// 对一些路径进行匹配并放行
authorize.matchers(PathRequest.toStaticResources().atCommonLocations())
.permitAll();
});
return http.build();
}
关闭跨域限制
// 关闭跨域限制
http.csrf(csrf -> csrf.disable());
更改用户登录行为 (Reactive 方面的)
在默认的Security的认证行为当中,是使用了内存生成临时的密码作为登录密码。
而Security 自己的密码认证行为,其实是使用了 http.authenticationManager() 方法进行管理,而 http.authenticationManager()
需要提供 ReactiveAuthenticationManager 类进行管理,以下是一些调用流程说明
- 1.Security 使用 SecurityWebFilterChain 作为请求的过滤器链
- 2.SecurityWebFilterChain 提供了一个请求配置对象 ServerHttpSecurity http
- 3.ServerHttpSecurity 对象可以对过滤链中的多种配置进行自定义设置,如 csrf(跨域),登录页(formLogin),请求路径匹配(authorizeExchange)等
- 请求路径匹配(authorizeExchange) 是重点,因为它可以设定那些路径需要登陆,哪些不需要
- 4.其中 ServerHttpSecurity 对象包含了认证管理 authenticationManager
- 5.认证管理 authenticationManager 需要传入一个对象 ReactiveAuthenticationManager
- 6.ReactiveAuthenticationManager 是一个接口规范,我们可以通过实现这个接口的方法来实现认证功能
- 7.ReactiveAuthenticationManager 接口下,官方已经提供了用于使用账号密码实现认证功能的实现类 UserDetailsRepositoryReactiveAuthenticationManager,如下图
- 8.我们可以使用 UserDetailsRepositoryReactiveAuthenticationManager 类对象提交给 ReactiveAuthenticationManager
- 9.UserDetailsRepositoryReactiveAuthenticationManager 实例化需要提供一个 ReactiveUserDetailsService 对象
- 10.ReactiveUserDetailsService 是一个接口,它是用于获得用户信息对象 UserDetails 类的
- 11.UserDetails 对象就是官方提供的用于存放用户信息的对象,后面的认证和授权都会基于 UserDetails 对象中的信息进行识别
- 12.我们通过创建一个实现类来实现 ReactiveUserDetailsService 方法
- 13.在实现类中我们通过查询数据库的方式来获得用户登录信息,并导入到 UserDetails 中。
- 14.UserDetails 本身也是一个接口,所以我们还需要对 UserDetails 进行实现。
- 也可以使用官方提供的 User.builder() 来实现 UserDetails
授权
THE END
0
二维码
打赏
海报
Spring Security Reactive
简介
了解 SpringSecurity 的自动配置默认行为: 所有请求都需要登陆才能访问
SecurityAutoConfiguration
导入了 SecurityFilterChain 组件,这个组件就是默认所有请求都需要登陆才可以访问……
TZMing花园 - 软件分享与学习

共有 0 条评论