Security6.2 中的SpEL 表达式应用(权限注解使用)

news/2025/2/21 16:32:24/

最近学习若依框架,里面的权限注解涉及到了SpEL表达式 @PreAuthorize("@ss.hasPermi('system:user:list')"),若依项目中用的是自己写的方法进行权限处理, 也可以只用security 来实现权限逻辑代码,下面写如何用security 实现。

security中  @PreAuthorize("hasPermission(Object target, Object permission)")  的hasPermission方法,是通过PermissionEvaluator实现,默认继承类是DenyAllPermissionEvaluator,所有方法返回false,所以注解后的结果只有拒绝权限;所以继承PermissionEvaluator重写hasPermission即可。

逻辑如下:

1、securityConfig文件上加入注解@EnableMethodSecurity,且引入自定义评估器:CustomPermissionEvaluator

2、编写CustomPermissionEvaluator文件

:security 6.2.1 中 EnableGlobalMethodSecurity 已弃用,改使用 EnableMethodSecurity 且prePostEnabled为ture,只需添加注解@EnableMethodSecurity 即可

package com.example.securityDemo.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;/*** @description: security配置类* @author: mml* @create: 2024/01/26*/
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {// 引入自定义评估器@Beanstatic MethodSecurityExpressionHandler methodSecurityExpressionHandler(CustomPermissionEvaluator permissionEvaluator) {DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();handler.setPermissionEvaluator(permissionEvaluator);return handler;}@BeanUserDetailsService userDetailsService(){UserDetails user = User.withDefaultPasswordEncoder().username("mml").password("123").roles("USER").authorities("system:user:update","system:user:list").build();return new InMemoryUserDetailsManager(user);}/*** 是Spring Security 过滤器链,Spring Security 中的所有功能都是通过这个链来提供的* @date 2024/1/26*/@BeanSecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {// 拦截所有请求,但是不经过任何过滤器
//        return new DefaultSecurityFilterChain(new AntPathRequestMatcher("/**"));httpSecurity.authorizeHttpRequests(p -> p.anyRequest().authenticated()).csrf(c -> c.disable()).formLogin((form) -> form.loginPage("/login").permitAll());return httpSecurity.build();}}

自定义评估器代码

import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;import java.io.Serializable;
import java.util.Collection;/*** @description: 自定义权限评估器* @author: mml* @create: 2024/02/17*/
@Component
public class CustomPermissionEvaluator implements PermissionEvaluator {AntPathMatcher antPathMatcher = new AntPathMatcher();@Overridepublic boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {// 获取当前用户的角色Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();for (GrantedAuthority authority : authorities) {// 权限判断if (antPathMatcher.match(authority.getAuthority(), (String) permission)){// 说明有权限return true;}}return false;}@Overridepublic boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {return false;}
}

接口层:

@RestController
public class UserController {@RequestMapping("/list")@PreAuthorize("hasPermission('/list','system:user:list')")public String list() {return "get list ";}@RequestMapping("/add")@PreAuthorize("hasPermission('/add','system:user:add')")public String add() {return "post add ";}
}

可以使用postman测试

测试结果如下:

list-有权限

add 方法-没有权限

security参考链接:方法安全 :: Spring Security


http://www.ppmy.cn/news/1357025.html

相关文章

Transformer面试十问

1 Scaled Dot-Product Attention中为什么要除以 d k \sqrt{d_k} dk​ ​? 1. 从纯数学上考虑&#xff1a;对于输入均值为0,方差为1的分布&#xff0c;点乘后结果其方差为dk&#xff0c;所以需要缩放一下。下图为原论文注释。 2. 从神经网络上考虑&#xff1a;防止在计算点积…

基于python+django+vue.js开发的健身房管理系统

功能介绍 平台采用B/S结构&#xff0c;后端采用主流的Python语言进行开发&#xff0c;前端采用主流的Vue.js进行开发。 功能包括&#xff1a;教练管理、会员管理、场地管理、设备管理、用户管理、日志管理、系统信息模块。 源码地址 https://github.com/geeeeeeeek/python_…

爬虫学习笔记-scrapy爬取电影天堂(双层网址嵌套)

1.终端运行scrapy startproject movie,创建项目 2.接口查找 3.终端cd到spiders,cd scrapy_carhome/scrapy_movie/spiders,运行 scrapy genspider mv https://dy2018.com/ 4.打开mv,编写代码,爬取电影名和网址 5.用爬取的网址请求,使用meta属性传递name ,callback调用自定义的…

openGauss学习笔记-220 openGauss性能调优-确定性能调优范围-查询最耗性能的SQL

文章目录 openGauss学习笔记-220 openGauss性能调优-确定性能调优范围-查询最耗性能的SQL220.1 操作步骤 openGauss学习笔记-220 openGauss性能调优-确定性能调优范围-查询最耗性能的SQL 系统中有些SQL语句运行了很长时间还没有结束&#xff0c;这些语句会消耗很多的系统性能&…

【机器学习案例4】为机器学习算法编码分类数据【含源码】

目录 编码分类数据 序数编码 标签编码 一次性编码 目标编码 目标编码的优点 目标编码的缺点 在现实生活中,收集的原始数据很少采用我们可以直接用于机器学习模型的格式,即数值型数据。因此,需要进行一些预处理,以便以正确的格式呈现数据、选择信息丰富的数据或降低其…

sql报错注入 之 floor 函数报错:主键重复

Mysql报错注入之floor报错详解 updatexml extractvalue floor 是mysql的函数 groupbyrandfloorcount 一、简述 利用 select count(*),(floor(rand(0)*2))x from table group by x&#xff0c;导致数据库报错&#xff0c;通过 concat 函数&#xff0c;连接注入语句与 floor…

thinkphp5.0提示不支持redis,not support: redis

安装PHP扩展 例如宝塔&#xff0c;其他环境请用命令行&#xff0c;安装 redis配置完成以后&#xff0c;修改php.ini把redis扩展打开即可&#xff0c;重启环境

SG3225EAN规格书

SG3225EAN 晶体振荡器利用先进的锁相环技术和AT切割晶体单元&#xff0c;提供了宽频率范围和高性能LV-PECL输出&#xff0c;73.5 MHz至700 MHz的宽频率范围&#xff0c;能够保证高稳定性和宽频率调整的能力&#xff0c;适应于多样化的应用需求。2.5V和3.3V两种供电电压&#xf…