一些权限方面的思考
- 背景
- 说明
- 自定义注解
- 解析自定义注解
背景
鉴权可以通过切面做抽取
说明
都是一些伪代码, 不能直接使用, 提供一种思路.
都是一些伪代码, 不能直接使用, 提供一种思路.
都是一些伪代码, 不能直接使用, 提供一种思路.
自定义注解
自定义注解: Permission
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Permission {Member.Role [] roles();Type type();enum Type {/*** 项目类型*/PROJECT,/*** 团队类型*/TEAM,/*** 系统管理类型*/SYSTEM}class Member {enum Role {/*** 角色001*/ROLE_001,/*** 角色002*/ROLE_002}}
}
解析自定义注解
伪代码实现: PermissionAspect
@Aspect
@Component
// @DependsOn({"springContextUtil"})
@Order(2)
@Slf4j
public class PermissionAspect {@Pointcut("@annotation(Permission)")private void annotationPointCut() {}@Around("annotationPointCut()")public Object before(ProceedingJoinPoint joinPoint) throws Throwable {RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();if (!(requestAttributes instanceof ServletRequestAttributes)) {throw new ClassCastException();}ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;HttpServletRequest request = attributes.getRequest();Signature signature = joinPoint.getSignature();if (!(signature instanceof MethodSignature)) {throw new ClassCastException();}MethodSignature methodSignature = (MethodSignature) signature;Method method = methodSignature.getMethod();// 获取当前访问人信息UserContext.UserInfo userInfo = UserContext.getInstance().getCurrentUser();if (userInfo == null) {throw new Exception();}// 如实是SuperAdmin直接放行// TODOPermission annotation = method.getAnnotation(Permission.class);// 方法配置的角色Permission.Member.Role[] roles = annotation.roles();// 方法指定的类型Permission.Type type = annotation.type();// 核心校验逻辑permissionCheck(request, roles, type, userInfo);return joinPoint.proceed();}/*** 人员角色鉴权** @param request 请求* @param permittedRoles 配置的授权角色数组* @param type 配置的类型* @param userInfo 当前用户信息*/private void permissionCheck(HttpServletRequest request, Permission.Member.Role[] permittedRoles, Permission.Type type, UserContext.UserInfo userInfo) throws Exception {boolean hasPermission = false;// TODO 只需要校验
// List<Role> roleList = xxx.getMemberRole(uuid, spaceId);
// hasPermission = CollectionUtil.containsAny(currentMemberRoles, Arrays.asList(permittedRoles));
// if (!hasPermission) {
// // "没有权限"
// throw new Exception();
// }}/*** // TODO 伪代码: 模拟用户上下文*/@Datastatic class UserContext {UserInfo currentUser;private UserContext(){}public static UserContext getInstance() {return null;}class UserInfo {}}
}