@PreAuthorize注解会在方法执行前进行权限验证,支持Spring EL表达式,它是基于方法注解的权限解决方案。只有当@EnableGlobalMethodSecurity(prePostEnabled=true)的时候,@PreAuthorize才可以使用,@EnableGlobalMethodSecurity注解在SPRING安全中心进行设置,如下:
/**
* SPRING安全中心
* @author ROCKY
*/
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
}
如何使用
①. 注解如何使用?文章来源:https://www.toymoban.com/news/detail-690602.html
@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));
}
②. 自定义权限实现 文章来源地址https://www.toymoban.com/news/detail-690602.html
@PreAuthorize("@pms.hasPermission('archsys_sysarchreport_view')" )
- pms是一个注册在 Spring容器中的Bean,对应的类是cn.hadoopx.framework.web.service.PermissionService;
- hasPermission是PermissionService类中定义的方法;
- 当Spring EL 表达式返回TRUE,则权限校验通过;
- 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();
}
}
到了这里,关于@PreAuthorize注解详解的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!