iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >基于SpringSecurity的@PreAuthorize怎么实现自定义权限校验
  • 941
分享到

基于SpringSecurity的@PreAuthorize怎么实现自定义权限校验

2023-07-05 20:07:28 941人浏览 独家记忆
摘要

这篇文章主要介绍“基于springSecurity的@PreAuthorize怎么实现自定义权限校验”,在日常操作中,相信很多人在基于SpringSecurity的@PreAuthorize怎么实现自定义权限校验问题上存在疑惑,小编查阅了各

这篇文章主要介绍“基于springSecurity的@PreAuthorize怎么实现自定义权限校验”,在日常操作中,相信很多人在基于SpringSecurity的@PreAuthorize怎么实现自定义权限校验问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”基于SpringSecurity的@PreAuthorize怎么实现自定义权限校验”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

一、前言

在我们一般的WEB系统中必不可少的就是权限的配置,也有经典的RBAC权限模型,是基于角色的权限控制。这是目前最常被开发者使用也是相对易用、通用权限模型。当然SpringSecurity已经实现了权限的校验,但是不够灵活,我们可以自己写一下校验条件,从而更加的灵活!

二、SpringSecurity的@PreAuthorize

@PreAuthorize("hasAuthority('system:dept:list')")@GetMapping("/hello")public String hello (){    return "hello";}

我们进去源码方法中看看具体实现,我们进行模仿!

// 调用的方法@Overridepublic final boolean hasAuthority(String authority) {return hasAnyAuthority(authority);}@Overridepublic final boolean hasAnyAuthority(String... authorities) {return hasAnyAuthorityName(null, authorities);}private boolean hasAnyAuthorityName(String prefix, String... roles) {Set<String> roleSet = getAuthoritySet();// 便利规则,看看是否有权限for (String role : roles) {String defaultedRole = getRoleWithDefaultPrefix(prefix, role);if (roleSet.contains(defaultedRole)) {return true;}}return false;}

三、权限校验判断工具

@Component("pms")public class PermissionService {public boolean hasPermission(String permission) {if (StrUtil.isBlank(permission)) {return false;}Authentication authentication = SecurityContextHolder.getContext().getAuthentication();if (authentication == null) {return false;}Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();return authorities.stream().map(GrantedAuthority::getAuthority).filter(StringUtils::hasText).anyMatch(x -> PatternMatchUtils.simpleMatch(permission, x));}}

四、controller使用

@GetMapping("/page" )@PreAuthorize("@pms.hasPermission('order_get')" )public R getOrderInPage(Page page, OrderInRequest request) {    return R.ok(orderInService.queryPage(page, request));}

参数说明:

主要是采用SpEL表达式语法,

@pms:是一个我们自己配置的spring容器起的别名,能够正确的找到这个容器类;

hasPermission('order_get'):容器内方法名称和参数

到此,关于“基于SpringSecurity的@PreAuthorize怎么实现自定义权限校验”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注编程网网站,小编会继续努力为大家带来更多实用的文章!

--结束END--

本文标题: 基于SpringSecurity的@PreAuthorize怎么实现自定义权限校验

本文链接: https://www.lsjlt.com/news/354853.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作