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

相关文章

这篇文章主要介绍了spring的事务传播属性REQUIRED_NESTED的原...
今天小编给大家分享的是一文解析spring中事务的传播机制,相...
这篇文章主要介绍了SpringCloudAlibaba和SpringCloud有什么区...
本篇文章和大家了解一下SpringCloud整合XXL-Job的几个步骤。...
本篇文章和大家了解一下Spring延迟初始化会遇到什么问题。有...
这篇文章主要介绍了怎么使用Spring提供的不同缓存注解实现缓...