1. 权限控制的基本思路
在企业级应用开发中,权限控制是保证系统安全性的重要环节。SpringBoot作为目前主流的Java开发框架,提供了多种方式来实现权限控制。其中基于注解的权限控制因其简洁性和灵活性,成为开发者的首选方案。
传统的单一注解权限控制(如@PreAuthorize)虽然简单易用,但在复杂业务场景下往往显得力不从心。我们需要一种能够支持多种权限判断逻辑、可灵活组合的解决方案。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 多注解权限方案设计
2.1 核心注解定义
首先我们需要定义几个核心注解:
java复制@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface RequirePermission {
String[] value();
Logical logical() default Logical.AND;
}
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface RequireRole {
String[] value();
Logical logical() default Logical.AND;
}
public enum Logical {
AND, OR
}
这种设计允许我们在方法或类级别声明权限要求,并通过logical参数指定多个权限间的逻辑关系(AND或OR)。
2.2 权限校验拦截器
接下来我们需要实现权限校验的核心逻辑:
java复制@Component
public class PermissionInterceptor implements HandlerInterceptor {
@Autowired
private PermissionService permissionService;
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
if (!(handler instanceof HandlerMethod)) {
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
// 检查类级别注解
Class<?> clazz = method.getDeclaringClass();
if (clazz.isAnnotationPresent(RequirePermission.class)) {
RequirePermission classAnnotation = clazz.getAnnotation(RequirePermission.class);
if (!checkPermission(classAnnotation)) {
throw new AccessDeniedException("权限不足");
}
}
// 检查方法级别注解
if (method.isAnnotationPresent(RequirePermission.class)) {
RequirePermission methodAnnotation = method.getAnnotation(RequirePermission.class);
if (!checkPermission(methodAnnotation)) {
throw new AccessDeniedException("权限不足");
}
}
// 角色检查逻辑类似...
return true;
}
private boolean checkPermission(RequirePermission annotation) {
String[] permissions = annotation.value();
Logical logical = annotation.logical();
if (logical == Logical.AND) {
return permissionService.hasAllPermissions(permissions);
} else {
return permissionService.hasAnyPermission(permissions);
}
}
}
3. 权限服务实现
3.1 权限服务接口
java复制public interface PermissionService {
boolean hasPermission(String permission);
boolean hasAllPermissions(String... permissions);
boolean hasAnyPermission(String... permissions);
boolean hasRole(String role);
boolean hasAllRoles(String... roles);
boolean hasAnyRole(String... roles);
}
3.2 基于Spring Security的实现
如果项目已经集成Spring Security,可以直接利用其提供的功能:
java复制@Service
public class SecurityPermissionService implements PermissionService {
@Override
public boolean hasPermission(String permission) {
return SecurityContextHolder.getContext()
