微服务鉴权全局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();
}
}
评论区