@PreAuthorize注解详解

@PreAuthorize注解会在方法执行前进行权限验证,支持Spring EL表达式,它是基于方法注解的权限解决方案。只有当@EnableGlobalMethodSecurity(prePostEnabled=true)的时候,@PreAuthorize才可以使用,@EnableGlobalMethodSecurity注解在SPRING安全中心进行设置,如下:
 

/**
 * SPRING安全中心
 * @author ROCKY
 */
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
}
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

如何使用

①. 注解如何使用?

@Operation(summary = "通过id查询档案报表", description = "通过id查询档案报表")
    @GetMapping("/{reportId}" )
    @PreAuthorize("@pms.hasPermission('archsys_sysarchreport_view')" )
    public R getById(@PathVariable("reportId" ) Long reportId) {
        return R.ok(sysArchReportService.getById(reportId));
    }
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

②. 自定义权限实现 

@PreAuthorize("@pms.hasPermission('archsys_sysarchreport_view')" )

  1. pms是一个注册在 Spring容器中的Bean,对应的类是cn.hadoopx.framework.web.service.PermissionService;
  2. hasPermission是PermissionService类中定义的方法;
  3. 当Spring EL 表达式返回TRUE,则权限校验通过;
  4. PermissionService.java的定义如下:
public class PermissionService {

	/**
	 * 判断接口是否有任意xxx,xxx权限
	 * @param permissions 权限
	 * @return {boolean}
	 */
	public boolean hasPermission(String... permissions) {
		if (ArrayUtil.isEmpty(permissions)) {
			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(permissions, x));
	}

}
@RequiredArgsConstructor
@EnableConfigurationProperties(PermitAllUrlProperties.class)
public class PigResourceServerAutoConfiguration {

	/**
	 * 鉴权具体的实现逻辑
	 * @return (#pms.xxx)
	 */
	@Bean("pms")
	public PermissionService permissionService() {
		return new PermissionService();
	}
}

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值