Java进阶指南
表达式解析
UEL 统一表达式语言
Ognl 对象图导航语言
Spel Spring表达式语言
Java 进阶
SPI的高级用法
SLF4J的绑定原理
H2 JDBC驱动类注册与数据库引擎初始化原理
Java SPI与Dubbo SPI区别
Java 秒懂对象 PO、VO、BO、DTO、POJO!
Java POJO/DO/DTO/BO/VO概念及应用案例分析
一个线程oom,进程里其他线程还能运行吗?
jps命令详解
Java的BigDecimal也会存在丢失精度的问题
java中的枚举类和常量类区别在哪儿?
Java 打包 FatJar 方法小结
"too many open files"的原理和解决方案
GraalVM 专栏
GraalVM入门以及环境搭建
Maven 专栏
maven 跳过单元测试-maven.test.skip和skipTests的区别
maven 配置代码检查插件,生成检查报告
Maven 执行生命周期
maven 删除本地仓库当前项目的依赖包
Gradle 专栏
自己动手应用Groovy实现Gradle的DSL—Task定义
看懂Gradle脚本(1)- Groovy语言的Map语法糖
看懂Gradle脚本(2)- Groovy语言的闭包语法
看懂Gradle脚本(3)- Groovy AST转换
看懂Gradle脚本(4)- Groovy语法之运算符重载
看懂Gradle脚本(5)- 跟Gradle学领域驱动设计
看懂Gradle脚本(6)- Hello Groovy, Goodbye Getters&Setters
看懂Gradle脚本(7)- ext {}函数是如何实现的
Gradle 常见问题集锦
Spring 专栏
Spring AOP 使用介绍,从前世到今生
Spring IOC 容器源码分析
Spring AOP 源码解析
Spring @PropertySource 注解实现读取 yml 文件
Spring 好用的工具类
Spring @Async失效情况
Spring I/O 2023 干货视频精选!
Spring 动态刷新bean
Spring Cache缓存技术
Spring @Transactional注解失效情况
Spring Event 事件订阅踩坑
循环依赖
Spring 解析@Async引起的循环依赖
Spring 中的循环依赖
从源码层面深度剖析 Spring 循环依赖 | 京东云技术团队
Spring 不同平台构建出现循环依赖错误问题原因分析
SpringBoot 专栏
SpringBoot 构建FarJAR Maven配置
SpringBoot 项目启动慢原因分析
SpringBoot 资源文件问题总结(Spring Boot的静态资源访问,配置文件外置)
SpringBoot 读取Jar包中静态资源原理
SpringBoot 配置Undertow处理高并发
SpringBoot Maven Profile配合Spring Profile进行多环境配置和打包
SpringBoot 使用profile结合maven实现多环境配置
SpringBoot @ComponentScan注解过滤排除不加载某个类的3种方法
Mybatis 专栏
Mybatis 一级、二级缓存机制
Mybatis 关闭一级、二级缓存机制
MybatisPlus
MybatisPlus LambdaQueryWrapper类的实现原理
MybatisPlus 在不修改全局策略和字段注解的情况下将字段更新为null
并发与多线程
Java 从单核到多核的多线程并发
并发和并行的区别
Redisson 专栏
一次生产redisson 延时队列不消费问题排查
redisson 阻塞队列不消费问题排查
Spring Batch 专栏
批处理框架spring batch基础知识介绍
Shiro 专栏
一篇适合小白的Shiro教程
SpringMVC 专栏
SpringMVC 后端处理多文件上传如何保持最大的灵活性
@RequestParam的加与不加的作用
SpringCloud 专栏
Gateway 一文彻底解决跨域问题
ruoyi-vue-pro 开发指南
萌新必读
简介
交流群
视频教程
功能列表
快速启动(后端项目)
快速启动(前端项目)
接口文档
技术选型
项目结构
代码热加载
一键改包
删除功能
内网穿透
达梦数据库专属
后端手册
新建模块
代码生成【单表】(新增功能)
代码生成【主子表】
代码生成【树表】
功能权限
数据权限
用户体系
三方登录
OAuth 2.0(SSO 单点登录)
SaaS多租户【字段隔离】
SaaS 多租户【数据库隔离】
WebSocket 实时通讯
异常处理(错误码)
参数校验、时间传参
分页实现
VO 对象转换、数据翻译
文件存储(上传下载)
Excel 导入导出
操作日志、访问日志、异常日志
MyBatis 数据库
MyBatis 联表&分页查询
多数据源(读写分离)、事务
Redis 缓存
本地缓存
异步任务
分布式锁
幂等性(防重复提交)
请求限流(RateLimiter)
单元测试
验证码
工具类
配置管理
数据库文档
中间件手册
定时任务
消息队列(内存)
消息队列(Redis)
消息队列(RocketMQ)
消息队列(RabbitMQ)
消息队列(Kafka)
限流熔断
工作流手册
工作流演示
功能开启
工作流(达梦适配)
审批接入(流程表单)
审批接入(业务表单)
流程设计器(BPMN)
流程设计器(钉钉、飞书)
选择审批人、发起人自选
会签、或签、依次审批
流程发起、取消、重新发起
审批通过、不通过、驳回
审批加签、减签
审批转办、委派、抄送
执行监听器、任务监听器
流程表达式
流程审批通知
大屏手册
报表设计器
大屏设计器
支付手册
功能开启
支付宝支付接入
微信公众号支付接入
微信小程序支付接入
支付宝、微信退款接入
会员手册
功能开启
微信公众号登录
微信小程序登录
会员用户、标签、分组
会员等级、积分、签到
商城手册
商城演示
功能开启
商城装修
【商品】商品分类
【商品】商品属性
【商品】商品 SPU 与 SKU
【商品】商品评价
【交易】购物车
【交易】交易订单
【交易】售后退款
【交易】快递发货
【交易】门店自提
【交易】分销返佣
【营销】优惠劵
【营销】拼团活动
【营销】秒杀活动
【营销】砍价活动
【营销】满减送
【营销】限时折扣
【营销】内容管理
【统计】会员、商品、交易统计
ERP手册
ERP 演示
功能开启
【产品】产品信息、分类、单位
【库存】产品库存、库存明细
【库存】其它入库、其它出库
【库存】库存调拨、库存盘点
【采购】采购订单、入库、退货
【销售】销售订单、出库、退货
【财务】采购付款、销售收款
CRM 手册
CRM 演示
功能开启
【线索】线索管理
【客户】客户管理、公海客户
【商机】商机管理、商机状态
【合同】合同管理、合同提醒
【回款】回款管理、回款计划
【产品】产品管理、产品分类
【通用】数据权限
【通用】跟进记录、待办事项
公众号手册
功能开启
公众号接入
公众号粉丝
公众号标签
公众号消息
自动回复
公众号菜单
公众号素材
公众号图文
公众号统计
系统手册
短信配置
邮件配置
站内信配置
数据脱敏
敏感词
地区 & IP 库
运维手册
开发环境
Linux 部署
Docker 部署
Jenkins 部署
HTTPS 证书
服务监控
前端手册 Vue 3.x
开发规范
菜单路由
Icon 图标
字典数据
系统组件
通用方法
配置读取
CRUD 组件
国际化
IDE 调试
代码格式化
前端手册 Vue 2.x
开发规范
菜单路由
Icon 图标
字典数据
系统组件
通用方法
配置读取
更新日志
【v2.1.0】开发中
【v2.0.1】2024-03-01
【v2.0.0】2024-01-26
【v1.9.0】2023-12-01
【v1.8.3】2023-10-24
yudao-cloud 开发指南
萌新必读
简介
交流群
视频教程
功能列表
快速启动(后端项目)
快速启动(前端项目)
接口文档
技术选型
项目结构
代码热加载
一键改包
删除功能
内网穿透
达梦数据库专属
微服务手册
微服务调试(必读)
注册中心 Nacos
配置中心 Nacos
服务网关 Spring Cloud Gateway
服务调用 Feign
定时任务 XXL Job
消息队列(内存)
消息队列(Redis)
消息队列(RocketMQ)
消息队列(RabbitMQ)
消息队列(Kafka)
消息队列(Cloud)
分布式事务 Seata
服务保障 Sentinel
Spring Security 专栏
Spring Security 入门
Spring Security OAuth2 入门
Spring Security OAuth2 存储器
Spring Security OAuth2 单点登录
Spring Security 常见问题
Guava 专栏
Guava 常用API汇总
本文档使用 MrDoc 发布
-
+
首页
功能权限
## [#](https://doc.iocoder.cn/resource-permission/#%F0%9F%91%8D-%E7%9B%B8%E5%85%B3%E8%A7%86%E9%A2%91%E6%95%99%E7%A8%8B)👍 相关视频教程 * [功能权限 01:如何设计一套权限系统?(opens new window)](https://t.zsxq.com/07nYzrfyz) * [功能权限 02:如何实现菜单的创建?(opens new window)](https://t.zsxq.com/07IuNBmAq) * [功能权限 03:如何实现角色的创建?(opens new window)](https://t.zsxq.com/07f6AuJuZ) * [功能权限 04:如何给用户分配权限 —— 将菜单赋予角色?(opens new window)](https://t.zsxq.com/07uJqV7Y3) * [功能权限 05:如何给用户分配权限 —— 将角色赋予用户?(opens new window)](https://t.zsxq.com/07YBe6QjA) * [功能权限 06:后端如何实现 URL 权限的校验?(opens new window)](https://t.zsxq.com/072ZVJurz) * [功能权限 07:前端如何实现菜单的动态加载?(opens new window)](https://t.zsxq.com/07rnMRRn2) * [功能权限 08:前端如何实现按钮的权限校验?(opens new window)](https://t.zsxq.com/072JeIUfY) ## [#](https://doc.iocoder.cn/resource-permission/#_1-rbac-%E6%9D%83%E9%99%90%E6%A8%A1%E5%9E%8B)1. RBAC 权限模型 系统采用 RBAC 权限模型,全称是 Role-Based Access Control 基于角色的访问控制。  简单来说,每个用户拥有若干角色,每个角色拥有若干个菜单,菜单中存在菜单权限、按钮权限。这样,就形成了 **“用户 <-> 角色 <-> 菜单”** 的授权模型。 在这种模型中,用户与角色、角色与菜单之间构成了多对多的关系,如下图:  ## [#](https://doc.iocoder.cn/resource-permission/#_2-token-%E8%AE%A4%E8%AF%81%E6%9C%BA%E5%88%B6)2. Token 认证机制 安全框架使用的是 [Spring Security **(opens new window)**](https://www.iocoder.cn/Spring-Boot/Spring-Security/?yudao)+ Token 方案,整体流程如下图所示:  ① 前端调用登录接口,使用账号密码获得到认证 Token。响应示例如下: ```json { "code":0, "msg":"", "data":{ "token":"d2a3cdbc6c53470db67a582bd115103f" } } ``` * 管理后台的登录实现,可见 [代码(opens new window)](https://github.com/YunaiV/ruoyi-vue-pro/blob/master/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/auth/AuthController.java#L56-L63) * 用户 App 的登录实现,可见 [代码(opens new window)](https://github.com/YunaiV/ruoyi-vue-pro/blob/master/yudao-module-member/yudao-module-member-biz/src/main/java/cn/iocoder/yudao/module/member/controller/app/auth/AppAuthController.java#L34-L41) 疑问:为什么不使用 Spring Security 内置的表单登录? Spring Security 的登录拓展起来不方便,例如说验证码、三方登录等等。 Token 存储在数据库中,对应 `system_oauth2_access_token` 访问令牌表的 `id` 字段。考虑到访问的性能,缓存在 Redis 的 [`oauth2_access_token:%s` **(opens new window)**](https://github.com/YunaiV/ruoyi-vue-pro/blob/master/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/redis/RedisKeyConstants.java#L21)键中。 疑问:为什么不使用 JWT(JSON Web Token)? JWT 是无状态的,无法实现 Token 的作废,例如说用户登出系统、修改密码等等场景。 推荐阅读 [《还分不清 Cookie、Session、Token、JWT?》 **(opens new window)**](https://www.iocoder.cn/Fight/Confused-about-cookies-sessions,-Tokens-JWT/?yudao)文章。 默认配置下,Token 有效期为 30 天,可通过 `system_oauth2_client` 表中 `client_id = default` 的记录进行自定义:  * 修改 `access_token_validity_seconds` 字段,设置访问令牌的过期时间,默认 1800 秒 = 30 分钟 * 修改 `refresh_token_validity_seconds` 字段,设置刷新令牌的过期时间,默认 2592000 秒 = 30 天 ② 前端调用其它接口,需要在请求头带上 Token 进行访问。请求头格式如下: ```bash ### Authorization: Bearer 登录时返回的 Token Authorization: Bearer d2a3cdbc6c53470db67a582bd115103f ``` * 具体的代码实现,可见 [TokenAuthenticationFilter **(opens new window)**](https://github.com/YunaiV/ruoyi-vue-pro/blob/master/yudao-framework/yudao-spring-boot-starter-security/src/main/java/cn/iocoder/yudao/framework/security/core/filter/TokenAuthenticationFilter.java) 过滤器 考虑到使用 Postman、Swagger 调试接口方便,提供了 **Token 的模拟机制** 。请求头格式如下: ```bash ### Authorization: Bearer test用户编号 Authorization: Bearer test1 ``` 其中 `"test"` 可自定义,配置项如下: ```yaml ### application-local.yaml yudao: security: mock-enable: true # 是否开启 Token 的模拟机制 mock-secret: test # Token 模拟机制的 Token 前缀 ``` ## [#](https://doc.iocoder.cn/resource-permission/#_3-%E6%9D%83%E9%99%90%E6%B3%A8%E8%A7%A3)3. 权限注解 ### [#](https://doc.iocoder.cn/resource-permission/#_3-1-preauthorize-%E6%B3%A8%E8%A7%A3)3.1 @PreAuthorize 注解 [`@PreAuthorize` **(opens new window)**](https://github.com/spring-projects/spring-security/blob/main/core/src/main/java/org/springframework/security/access/prepost/PreAuthorize.java)是 Spring Security 内置的**前置**权限注解,添加在**接口方法**上,声明需要的权限,实现访问权限的控制。 ① 基于【权限标识】的权限控制 权限标识,对应 `system_menu` 表的 `permission` 字段,推荐格式为 `${系统}:${模块}:${操作}`,例如说 `system:admin:add` 标识 system 服务的添加管理员。 使用示例如下: ```java // 符合 system:user:list 权限要求 @PreAuthorize("@ss.hasPermission('system:user:list')") // 符合 system:user:add 或 system:user:edit 权限要求即可 @PreAuthorize("@ss.hasAnyPermissions('system:user:add,system:user:edit')") ``` ② 基于【角色标识】的权限控制 权限标识,对应 `system_role` 表的 `code` 字段, 例如说 `super_admin` 超级管理员、`tenant_admin` 租户管理员。 使用示例如下: ```java // 属于 user 角色 @PreAuthorize("@ss.hasRole('user')") // 属于 user 或者 admin 之一 @PreAuthorize("@ss.hasAnyRoles('user,admin')") ``` 实现原理是什么? 当 `@PreAuthorize` 注解里的 Spring EL 表达式返回 `false` 时,表示没有权限。 而 `@PreAuthorize("@ss.hasPermission('system:user:list')")` 表示调用 Bean 名字为 `ss` 的 `#hasPermission(...)` 方法,方法参数为 `"system:user:list"` 字符串。`ss` 对应的 Bean 是 [PermissionServiceImpl **(opens new window)**](https://github.com/YunaiV/ruoyi-vue-pro/blob/master/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/PermissionServiceImpl.java#L43) 类,所以你只需要去看该方法的[实现代码 **(opens new window)**](https://github.com/YunaiV/ruoyi-vue-pro/blob/master/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/PermissionServiceImpl.java#L293-L326)。 ### [#](https://doc.iocoder.cn/resource-permission/#_3-2-preauthenticated-%E6%B3%A8%E8%A7%A3)3.2 @PreAuthenticated 注解 [`@PreAuthenticated` **(opens new window)**](https://github.com/YunaiV/ruoyi-vue-pro/blob/master/yudao-framework/yudao-spring-boot-starter-security/src/main/java/cn/iocoder/yudao/framework/security/core/annotations/PreAuthenticated.java)是项目自定义的**认证**注解,添加在**接口方法**上,声明登录的用户才允许访问。 主要使用场景是,针对用户 App 的 `/app-app/**` 的 RESTful API 接口,默认是无需登录的,通过 `@PreAuthenticated` 声明它需要进行登录。使用示例如下: ```java // AppAuthController.java @PostMapping("/update-password") @Operation(summary = "修改用户密码", description = "用户修改密码时使用") @PreAuthenticated public CommonResult<Boolean> updatePassword(@RequestBody @Valid AppAuthUpdatePasswordReqVO reqVO) { // ... 省略代码 } ``` 具体的代码实现,可见 [PreAuthenticatedAspect **(opens new window)**](https://github.com/YunaiV/ruoyi-vue-pro/blob/master/yudao-framework/yudao-spring-boot-starter-security/src/main/java/cn/iocoder/yudao/framework/security/core/aop/PreAuthenticatedAspect.java) 类。 ## [#](https://doc.iocoder.cn/resource-permission/#_4-%E8%87%AA%E5%AE%9A%E4%B9%89%E6%9D%83%E9%99%90%E9%85%8D%E7%BD%AE)4. 自定义权限配置 默认配置下,管理后台的 `/admin-api/**` 所有 API 接口都**必须**登录后才允许访问,用户 App 的 `/app-api/**` 所有 API 接口**无需**登录就可以访问。 如下想要自定义权限配置,设置定义 API 接口可以匿名(不登录)进行访问,可以通过下面三种方式: ### [#](https://doc.iocoder.cn/resource-permission/#_4-1-%E6%96%B9%E5%BC%8F%E4%B8%80-%E8%87%AA%E5%AE%9A%E4%B9%89-authorizerequestscustomizer-%E5%AE%9E%E7%8E%B0)4.1 方式一:自定义 AuthorizeRequestsCustomizer 实现 每个 Maven Module 可以实现自定义的 [AuthorizeRequestsCustomizer **(opens new window)**](https://github.com/YunaiV/ruoyi-vue-pro/blob/master/yudao-framework/yudao-spring-boot-starter-security/src/main/java/cn/iocoder/yudao/framework/security/config/YudaoWebSecurityConfigurerAdapter.java)Bean,额外定义每个 Module 的 API 接口的访问规则。例如说 `yudao-module-infra` 模块的 [SecurityConfiguration **(opens new window)**](https://github.com/YunaiV/ruoyi-vue-pro/blob/master/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/framework/security/config/SecurityConfiguration.java) 类,代码如下: ① JDK 8 + Spring Boot 2.X 版本: ```java @Configuration("infraSecurityConfiguration") public class SecurityConfiguration { @Value("${spring.boot.admin.context-path:''}") private String adminSeverContextPath; @Bean("infraAuthorizeRequestsCustomizer") public AuthorizeRequestsCustomizer authorizeRequestsCustomizer() { return new AuthorizeRequestsCustomizer() { @Override public void customize(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry) { // Swagger 接口文档 registry.antMatchers("/swagger-ui.html").anonymous() .antMatchers("/swagger-resources/**").anonymous() .antMatchers("/webjars/**").anonymous() .antMatchers("/*/api-docs").anonymous(); // Spring Boot Actuator 的安全配置 registry.antMatchers("/actuator").anonymous() .antMatchers("/actuator/**").anonymous(); // Druid 监控 registry.antMatchers("/druid/**").anonymous(); // Spring Boot Admin Server 的安全配置 registry.antMatchers(adminSeverContextPath).anonymous() .antMatchers(adminSeverContextPath + "/**").anonymous(); } }; } } ``` ② JDK 21 + Spring Boot 3.X 版本: ```java @Configuration(proxyBeanMethods = false, value = "infraSecurityConfiguration") public class SecurityConfiguration { @Value("${spring.boot.admin.context-path:''}") private String adminSeverContextPath; @Bean("infraAuthorizeRequestsCustomizer") public AuthorizeRequestsCustomizer authorizeRequestsCustomizer() { return new AuthorizeRequestsCustomizer() { @Override public void customize(AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizationManagerRequestMatcherRegistry registry) { // Swagger 接口文档 registry.requestMatchers("/v3/api-docs/**").permitAll() .requestMatchers("/swagger-ui.html").permitAll() .requestMatchers("/swagger-ui/**").permitAll() .requestMatchers("/swagger-resources/**").permitAll() .requestMatchers("/webjars/**").permitAll() .requestMatchers("/*/api-docs").permitAll(); // Spring Boot Actuator 的安全配置 registry.requestMatchers("/actuator").permitAll() .requestMatchers("/actuator/**").permitAll(); // Druid 监控 registry.requestMatchers("/druid/**").permitAll(); // Spring Boot Admin Server 的安全配置 registry.requestMatchers(adminSeverContextPath).permitAll() .requestMatchers(adminSeverContextPath + "/**").permitAll(); // 文件读取 registry.requestMatchers(buildAdminApi("/infra/file/*/get/**")).permitAll(); } }; } } ``` 友情提示 * `permitAll()` 方法:所有用户可以任意访问,包括带上 Token 访问 * `anonymous()` 方法:匿名用户可以任意访问,带上 Token 访问会报错 如果你对 Spring Security 了解不多,可以阅读艿艿写的 [《芋道 Spring Boot 安全框架 Spring Security 入门 》 **(opens new window)**](https://www.iocoder.cn/Spring-Boot/Spring-Security/?yudao)文章。 ### [#](https://doc.iocoder.cn/resource-permission/#_4-2-%E6%96%B9%E5%BC%8F%E4%BA%8C-permitall-%E6%B3%A8%E8%A7%A3)4.2 方式二:`@PermitAll` 注解 在 API 接口上添加 [`@PermitAll` **(opens new window)**](https://javaee.github.io/javaee-spec/javadocs/javax/annotation/security/PermitAll.html)注解,示例如下: ```java // FileController.java @GetMapping("/{configId}/get/{path}") @PermitAll public void getFileContent(HttpServletResponse response, @PathVariable("configId") Long configId, @PathVariable("path") String path) throws Exception { // ... } ``` ### [#](https://doc.iocoder.cn/resource-permission/#_4-3-%E6%96%B9%E5%BC%8F%E4%B8%89-yudao-security-permit-all-urls-%E9%85%8D%E7%BD%AE%E9%A1%B9)4.3 方式三:`yudao.security.permit-all-urls` 配置项 在 `application.yaml` 配置文件,通过 `yudao.security.permit-all-urls` 配置项设置,示例如下: ```yaml yudao: security: permit-all-urls: - /admin-ui/** # /resources/admin-ui 目录下的静态资源 - /admin-api/xxx/yyy ```
LazzMan
2024年4月25日 19:46
转发文档
收藏文档
上一篇
下一篇
手机扫码
复制链接
手机扫一扫转发分享
复制链接
Markdown文件
PDF文档(打印)
分享
链接
类型
密码
更新密码