侧边栏壁纸
  • 累计撰写 22 篇文章
  • 累计创建 10 个标签
  • 累计收到 5 条评论

目 录CONTENT

文章目录

微服务AOP统一鉴权

AF
AF
2023-08-07 / 0 评论 / 0 点赞 / 72 阅读 / 2574 字

微服务鉴权全局AOP

// 定义注解
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ShouldAuth {
    boolean shouldLogin() default true;
}
// 定义注解切面
@Component
@Aspect
@Slf4j
public class ShouldAuthAspect {
    // 鉴权服务
    @Resource
    SessionClient sessionClient;

    @Pointcut("@annotation(com.yangxuan.library.auth.annotation.ShouldAuth) || @within(com.yangxuan.library.auth.annotation.ShouldAuth)")
    public void shouldAuth() {
    }

    @Around("shouldAuth()")
    public Object doBefore(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        ShouldAuth shouldAuthAnnotation;

        // 作用在方法上
        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();

        shouldAuthAnnotation = AnnotationUtils.findAnnotation(methodSignature.getMethod(), ShouldAuth.class);

        // 作用在类上
        if (shouldAuthAnnotation == null) {
            shouldAuthAnnotation = AnnotationUtils.findAnnotation(proceedingJoinPoint.getTarget().getClass(), ShouldAuth.class);
        }

        // 如果注解存在,且shouldLogin属性为false, 则绕过鉴权
        if (shouldAuthAnnotation != null && !shouldAuthAnnotation.shouldLogin()) {
            return proceedingJoinPoint.proceed();
        }

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        assert attributes != null;

        HttpServletRequest request = attributes.getRequest();
        String authorization = request.getHeader("authorization");

        if (StrUtil.isBlank(authorization)) {
            throw new BusinessException(ResultCode.UNAUTHORIZED);
        }

        String accessToken = authorization.replaceAll("Bearer ", "");
        
        // 鉴权信息获取
        AccessTokenParseResponse accessTokenParseResponse = sessionClient.parseToken(accessToken);
       
        if (accessTokenParseResponse == null) {
            throw new BusinessException(ResultCode.UNAUTHORIZED);
        }
        
        // 构建线程变量
        TenantContext tenantContext = TenantContext.get();
        
        if (tenantContext == null) {
            tenantContext = new TenantContext();
        }
        
        tenantContext.setTenantId(accessTokenParseResponse.getTenantId());
        tenantContext.setUserId(accessTokenParseResponse.getUserId());
        tenantContext.setUserType(accessTokenParseResponse.getUserType());
        TenantContext.set(tenantContext);
        return proceedingJoinPoint.proceed();
    }
}
0

评论区