微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

基于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";
}

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

// 调用方法
@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怎么实现自定义权限校验”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注编程之家网站,小编会继续努力为大家带来更多实用的文章

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐