@PreAuthorize注解会在方法执行前进行权限验证,支持Spring EL表达式,它是基于方法注解的权限解决方案。只有当@EnableGlobalMethodSecurity(prePostEnabled=true)的时候,@PreAuthorize才可以使用,@EnableGlobalMethodSecurity注解在SPRING安全中心进行设置,如下:
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)public class SecurityConfig extends WebSecurityConfigurerAdapter {}
如何使用
@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)); }
②. 自定义权限实现
@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 {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 {@Bean("pms")public PermissionService permissionService() {return new PermissionService();}}
来源地址:https://blog.csdn.net/m0_61916154/article/details/130125056