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

发布时间:2023-03-31 14:25:16 作者:iii
来源:亿速云 阅读:123

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

一、前言

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

二、SpringSecurity的@PreAuthorize

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

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

// 调用的方法
@Override
public final boolean hasAuthority(String authority) {
	return hasAnyAuthority(authority);
}

@Override
public 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 {

	/**
	 * 判断接口是否有xxx:xxx权限
	 * @param permission 权限
	 * @return {boolean}
	 */
	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怎么实现自定义权限校验”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

推荐阅读:
  1. SpringBoot +spring security 与CSRF有关的几个 问题
  2. SpringSecurity认证和授权的概念和用法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springsecurity

上一篇:Vue实现自动检测及版本更新的方法是什么

下一篇:HDFS Balancer负载均衡器及语法怎么使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》