Reactor 响应式编程(第四篇:Spring Security Reactive)

系列文章目录

Reactor 响应式编程(第一篇:Reactor核心)
Reactor 响应式编程(第二篇:Spring Webflux)
Reactor 响应式编程(第三篇:R2DBC)
Reactor 响应式编程(第四篇:Spring Security Reactive)


文章目录

  • 系列文章目录
  • 1. 整合
  • 2. 开发
    • 2.1 应用安全
    • 2.2 RBAC权限模型
  • 3. 认证
    • 3.1 静态资源放行
    • 3.2 其他请求需要登录
  • 4. 授权


1. 整合

目标:
SpringBoot + Webflux + Spring Data R2DBC + Spring Security

任务:

  • RBAC权限模型
  • WebFlux配置:@EnableWebFluxSecurity、@EnableReactiveMethodSecurity
  • SecurityFilterChain 组件
  • AuthenticationManager 组件
  • UserDetailsService 组件
  • 基于注解的方法级别授权
    <dependencies><!-- https://mvnrepository.com/artifact/io.asyncer/r2dbc-mysql --><dependency><groupId>io.asyncer</groupId><artifactId>r2dbc-mysql</artifactId><version>1.0.5</version></dependency><!--        响应式 Spring Data R2dbc--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-r2dbc</artifactId></dependency><!--        响应式Web  --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webflux</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency></dependencies>

2. 开发

2.1 应用安全

  • 防止攻击:
    • DDos、CSRF、XSS、SQL注入…
  • 控制权限
    • 登录的用户能干什么。
    • 用户登录系统以后要控制住用户的所有行为,防止越权;
  • 传输加密
    • https
    • X509
  • 认证:
    • OAuth2.0
    • JWT

2.2 RBAC权限模型

Role Based Access Controll: 基于角色的访问控制


一个网站有很多用户: zhangsan
每个用户可以有很多角色
一个角色可以关联很多权限
一个人到底能干什么?

权限控制:

  • 找到这个人,看他有哪些角色,每个角色能拥有哪些权限。 这个人就拥有一堆的 角色 或者 权限
  • 这个人执行方法的时候,我们给方法规定好权限,由权限框架负责判断,这个人是否有指定的权限

所有权限框架:

  • 让用户登录进来: 认证(authenticate):用账号密码、各种其他方式,先让用户进来
  • 查询用户拥有的所有角色和权限: 授权(authorize): 每个方法执行的时候,匹配角色或者权限来判定用户是否可以执行这个方法

导入Spring Security:默认效果


3. 认证

3.1 静态资源放行

3.2 其他请求需要登录

package com.atguigu.security.config;import com.atguigu.security.component.AppReactiveUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.reactive.PathRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.UserDetailsRepositoryReactiveAuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.server.SecurityWebFilterChain;/*** @author lfy* @Description* @create 2023-12-24 21:39*/
@Configuration
@EnableReactiveMethodSecurity //开启响应式 的 基于方法级别的权限控制
public class AppSecurityConfiguration {@AutowiredReactiveUserDetailsService appReactiveUserDetailsService;@BeanSecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {//1、定义哪些请求需要认证,哪些不需要http.authorizeExchange(authorize -> {//1.1、允许所有人都访问静态资源;authorize.matchers(PathRequest.toStaticResources().atCommonLocations()).permitAll();//1.2、剩下的所有请求都需要认证(登录)authorize.anyExchange().authenticated();});//2、开启默认的表单登录http.formLogin(formLoginSpec -> {
//            formLoginSpec.loginPage("/haha");});//3、安全控制:http.csrf(csrfSpec -> {csrfSpec.disable();});// 目前认证: 用户名 是 user  密码是默认生成。// 期望认证: 去数据库查用户名和密码//4、配置 认证规则: 如何去数据库中查询到用户;// Sprinbg Security 底层使用 ReactiveAuthenticationManager 去查询用户信息// ReactiveAuthenticationManager 有一个实现是//   UserDetailsRepositoryReactiveAuthenticationManager: 用户信息去数据库中查//   UDRespAM 需要  ReactiveUserDetailsService:// 我们只需要自己写一个 ReactiveUserDetailsService: 响应式的用户详情查询服务http.authenticationManager(new UserDetailsRepositoryReactiveAuthenticationManager(appReactiveUserDetailsService));//        http.addFilterAt()//构建出安全配置return http.build();}@Primary@BeanPasswordEncoder passwordEncoder(){PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();return encoder;}
}

在这里插入图片描述
这个界面点击登录,最终Spring Security 框架会使用 ReactiveUserDetailsService 组件,按照 表单提交的用户名 去数据库查询这个用户详情(基本信息[账号、密码],角色,权限);
把数据库中返回的 用户详情 中的密码 和 表单提交的密码进行比对。比对成功则登录成功;

package com.atguigu.security.component;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.r2dbc.core.DatabaseClient;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;/*** @author lfy* @Description* @create 2023-12-24 21:57*/
@Component  // 来定义如何去数据库中按照用户名查用户
public class AppReactiveUserDetailsService implements ReactiveUserDetailsService {@AutowiredDatabaseClient databaseClient;// 自定义如何按照用户名去数据库查询用户信息@AutowiredPasswordEncoder passwordEncoder;@Overridepublic Mono<UserDetails> findByUsername(String username) {//        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();//从数据库查询用户、角色、权限所有数据的逻辑Mono<UserDetails> userDetailsMono = databaseClient.sql("select u.*,r.id rid,r.name,r.value,pm.id pid,pm.value pvalue,pm.description " +"from t_user u " +"left join t_user_role ur on ur.user_id=u.id " +"left join t_roles r on r.id = ur.role_id " +"left join t_role_perm rp on rp.role_id=r.id " +"left join t_perm pm on rp.perm_id=pm.id " +"where u.username = ? limit 1").bind(0, username).fetch().one()// all().map(map -> {UserDetails details = User.builder().username(username).password(map.get("password").toString())//自动调用密码加密器把前端传来的明文 encode
//                            .passwordEncoder(str-> passwordEncoder.encode(str)) //为啥???//权限
//                            .authorities(new SimpleGrantedAuthority("ROLE_delete")) //默认不成功.roles("admin", "sale","haha","delete") //ROLE成功.build();//角色和权限都被封装成 SimpleGrantedAuthority// 角色有 ROLE_ 前缀, 权限没有// hasRole:hasAuthorityreturn details;});return userDetailsMono;}
}

4. 授权

@EnableReactiveMethodSecurity

package com.atguigu.security.controller;import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;/*** @author lfy* @Description* @create 2023-12-24 21:31*/
@RestController
public class HelloController {@PreAuthorize("hasRole('admin')")@GetMapping("/hello")public Mono<String> hello(){return Mono.just("hello world!");}// 角色 haha: ROLE_haha:角色// 没有ROLE 前缀是权限//复杂的SpEL表达式@PreAuthorize("hasRole('delete')")@GetMapping("/world")public Mono<String> world(){return Mono.just("world!!!");}
}

官方实例
配置是: SecurityWebFilterChain

package com.atguigu.security.config;import com.atguigu.security.component.AppReactiveUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.reactive.PathRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.UserDetailsRepositoryReactiveAuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.server.SecurityWebFilterChain;/*** @author lfy* @Description* @create 2023-12-24 21:39*/
@Configuration
@EnableReactiveMethodSecurity //开启响应式 的 基于方法级别的权限控制
public class AppSecurityConfiguration {@AutowiredReactiveUserDetailsService appReactiveUserDetailsService;@BeanSecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {//1、定义哪些请求需要认证,哪些不需要http.authorizeExchange(authorize -> {//1.1、允许所有人都访问静态资源;authorize.matchers(PathRequest.toStaticResources().atCommonLocations()).permitAll();//1.2、剩下的所有请求都需要认证(登录)authorize.anyExchange().authenticated();});//2、开启默认的表单登录http.formLogin(formLoginSpec -> {
//            formLoginSpec.loginPage("/haha");});//3、安全控制:http.csrf(csrfSpec -> {csrfSpec.disable();});// 目前认证: 用户名 是 user  密码是默认生成。// 期望认证: 去数据库查用户名和密码//4、配置 认证规则: 如何去数据库中查询到用户;// Sprinbg Security 底层使用 ReactiveAuthenticationManager 去查询用户信息// ReactiveAuthenticationManager 有一个实现是//   UserDetailsRepositoryReactiveAuthenticationManager: 用户信息去数据库中查//   UDRespAM 需要  ReactiveUserDetailsService:// 我们只需要自己写一个 ReactiveUserDetailsService: 响应式的用户详情查询服务http.authenticationManager(new UserDetailsRepositoryReactiveAuthenticationManager(appReactiveUserDetailsService));//构建出安全配置return http.build();}@Primary@BeanPasswordEncoder passwordEncoder(){PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();return encoder;}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/64341.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【Qt】信号、槽

目录 一、信号和槽的基本概念 二、connect函数&#xff1a;关联信号和槽 例子&#xff1a; 三、自定义信号和槽 1.自定义槽函数 2.自定义信号函数 例子&#xff1a; 四、带参的信号和槽 例子&#xff1a; 五、Q_OBJECT宏 六、断开信号和槽的连接 例子&#xff1a; …

数据库密码加密

数据库密码加密 简单来说&#xff1a; 我们会经常看到重置密码&#xff0c;小时候就会有疑惑&#xff0c;为什么不直接告诉我们密码&#xff0c;原来服务器自己也不知道。 我们都知道密码在数据库中不能明文&#xff0c;不然风险很高&#xff0c;有数据库权限的人还可能恶意利…

PCIE概述

PCIE概述 文章目录 PCIE概述前言一、应用场景二、PCIE理论2.1 硬件2.2 拓扑结构&#xff1a;处理器和设备之间的关系2.3 速率2.4 层次接口2.5 四种请求类型2.5.1 bar空间2.5.2 memory2.5.3 IO2.5.4 configuration2.5.5 message 前言 参考链接&#xff1a; pcie总线知识点解析 …

Android Studio创建新项目并引入第三方so外部aar库驱动NFC读写器读写IC卡

本示例使用设备&#xff1a;https://item.taobao.com/item.htm?spma21dvs.23580594.0.0.52de2c1bbW3AUC&ftt&id615391857885 一、打开Android Studio,点击 File> New>New project 菜单&#xff0c;选择 要创建的项目模版&#xff0c;点击 Next 二、输入项目名称…

NX系列-使用 `nmcli` 命令创建 Wi-Fi 热点并设置固定 IP 地址

使用 nmcli 命令创建 Wi-Fi 热点并设置固定 IP 地址 一、前言 在一些场景下&#xff0c;我们需要将计算机或嵌入式设备&#xff08;例如 NVIDIA Orin NX&#xff09;转换为 Wi-Fi 热点&#xff0c;以便其他设备&#xff08;如手机、笔记本等&#xff09;能够连接并使用该设备…

AngularJS 与 SQL 的集成应用

AngularJS 与 SQL 的集成应用 引言 在当今的Web开发领域,AngularJS 和 SQL 是两种非常重要的技术。AngularJS,作为一个强大的前端框架,能够帮助开发者构建复杂且高性能的客户端应用。而SQL(Structured Query Language),作为一种广泛使用的数据库查询语言,是管理关系型…

用docker快速安装电子白板Excalidraw绘制流程图

注&#xff1a;本文操作以debian12.8 最小化安装环境为host系统。 一、彻底卸载原有的残留 apt-get purge docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin docker-ce-rootless-extras 二、设置docker的安装源 # Add Dockers official G…

C++趟坑学习-new,delete,虚析构函数

#include <iostream> using namespace std;class Resource { public:Resource() { cout << "Resource constructed" << endl; }~Resource() { cout << "Resource destructed" << endl; } };int main() {// 动态分配一个包含…

Spring Mvc面试题(常见)

1 Spring MVC的执行流程 用户发起请求,请求先被Servlet拦截以后,转发给SpringMVC框架SpringMVC 里面的DispatcherServlet(核心控制器) 接收到请求,并转发给HandlerMappingHandlerMapping负责解析请求,根据请求信息和配置信息找到匹配的Controller类(当这里有配置拦截器,会…

mac 如何开启指定端口供外部访问?

前言 需要 mac 上开放指定端口&#xff0c;指定 ip 访问 解决 在 macOS 上开放一个端口&#xff0c;并指定只能特定的 IP 访问&#xff0c;可以使用 macOS 内置的 pfctl(Packet Filter)工具来实现。 1、 编辑 pf 配置文件&#xff1a; 打开 /etc/pf.conf 文件进行编辑。 可以使…

如何设置Jsoup解析京东商品详情?

在数字化时代&#xff0c;数据的价值日益凸显&#xff0c;尤其是在电商领域。通过爬虫技术&#xff0c;我们可以从网站中提取有价值的信息&#xff0c;用于市场分析、价格监控等。Java作为一种成熟且功能强大的编程语言&#xff0c;拥有丰富的库支持&#xff0c;使其成为编写爬…

STM32读写flash注意事项

STM32读写Flash时,需要注意以下事项以确保操作的正确性和可靠性: 一、写入操作注意事项 擦除操作: STM32内置Flash的写入操作必须遵循“先擦除,后写入”的原则。擦除操作以页(或扇区)为单位进行,这意味着在写入新数据之前,需要擦除整个页(或扇区)。写入单位: 写入操…

练习题:一维数组

练习题 第一题 键盘录入一组数列&#xff0c;利用冒泡排序将数据由大到小排序 代码 #include <stdio.h>int arr_home01() {int arr[10];int i,j,temp;printf("请输入10个测试整数&#xff1a;\n");int len sizeof(arr) / sizeof(arr[0]);for(i 0;i < …

手眼标定工具操作文档

1.手眼标定原理介绍 术语介绍 手眼标定&#xff1a;为了获取相机与机器人坐标系之间得位姿转换关系&#xff0c;需要对相机和机器人坐标系进行标定&#xff0c;该标定过程成为手眼标定&#xff0c;用于存储这一组转换关系的文件称为手眼标定文件。 ETH&#xff1a;即Eye To …

PyTorch中apex的安装方式

apex是NVIDIA开发的基于PyTorch的混合精度训练加速神器&#xff0c;能够增加运算速度&#xff0c;并且减少显存的占用。 Github地址&#xff1a;https://github.com/NVIDIA/apex官方教程&#xff1a;https://nvidia.github.io/apex/ 安装方式 需要注意的是apex的安装不能通过…

【YashanDB知识库】YCP单机部署离线升级-rpc升级方式详细步骤

前提&#xff1a;每个被纳管的主机必须开放9072端口 1、先执行备份操作 #ycm安装路径为默认/opt/ycmcd /opt/ycm/ycm/scripts[yashanecs-ba94-0001 scripts]$ sudo ./backup.sh -n ycm -i /opt/ycm/ycm -c yashandb -y /home/yashan/yasdb_home/yashandb/22.2.11.105 --cata-…

MyBatis一二级缓存的区别?

大家好&#xff0c;我是锋哥。今天分享关于【MyBatis一二级缓存的区别&#xff1f;】面试题。希望对大家有帮助&#xff1b; MyBatis一二级缓存的区别&#xff1f; 1000道 互联网大厂Java工程师 精选面试题-Java资源分享网 MyBatis 的缓存机制分为 一级缓存 和 二级缓存&…

mybatis 的动态sql 和缓存

动态SQL 可以根据具体的参数条件&#xff0c;来对SQL语句进行动态拼接。 比如在以前的开发中&#xff0c;由于不确定查询参数是否存在&#xff0c;许多人会使用类似于where 1 1 来作为前缀&#xff0c;然后后面用AND 拼接要查询的参数&#xff0c;这样&#xff0c;就算要查询…

某名校考研自命题C++程序设计——近10年真题汇总(下)

第二期&#xff0c;相比上一贴本帖的题目难度更高一些&#xff0c;我当然不会告诉你我先挑简单的写~ 某名校考研自命题C程序设计——近10年真题汇总&#xff08;上&#xff09;-CSDN博客文章浏览阅读651次&#xff0c;点赞9次&#xff0c;收藏13次。本帖更新一些某校的编程真题…

【网络】传输层协议UDP/TCP网络层IP数据链路层MACNAT详解

主页&#xff1a;醋溜马桶圈-CSDN博客 专栏&#xff1a;计算机网络原理_醋溜马桶圈的博客-CSDN博客 gitee&#xff1a;mnxcc (mnxcc) - Gitee.com 目录 1.传输层协议 UDP 1.1 传输层 1.2 端口号 1.3 UDP 协议 1.3.1 UDP 协议端格式 1.3.2 UDP 的特点 1.3.3 面向数据报 1…