@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 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();
	}
}

你可能感兴趣的:(Spring,Boot,spring,java,mybatis)