package quant.rich.emoney.component; import org.apache.commons.lang3.StringUtils; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import quant.rich.emoney.client.EmoneyClient; import quant.rich.emoney.entity.sqlite.ProxySetting; import quant.rich.emoney.entity.sqlite.RequestInfo; import quant.rich.emoney.service.sqlite.ProxySettingService; import quant.rich.emoney.service.sqlite.RequestInfoService; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; @Component @Aspect public class RequireAuthAndProxyAspect { @Autowired RequestInfoService requestInfoService; @Autowired ProxySettingService proxySettingService; @Around("@annotation(quant.rich.emoney.component.RequireAuthAndProxyAspect.RequireAuthAndProxy)") public Object around(ProceedingJoinPoint pjp) throws Throwable { ProxySetting defualtProxySetting = proxySettingService.getDefaultProxySetting(); if (defualtProxySetting == null) { throw new RuntimeException("需要配置默认代理设置"); } RequestInfo defaultRequestInfo = requestInfoService.getDefaultRequestInfo(); if (defaultRequestInfo == null) { throw new RuntimeException("需要配置默认请求信息"); } MethodSignature signature = (MethodSignature) pjp.getSignature(); Method method = signature.getMethod(); RequireAuthAndProxy annotation = method.getAnnotation(RequireAuthAndProxy.class); if (StringUtils.isBlank(defaultRequestInfo.getAuthorization())) { if (!annotation.autoLogin()) { throw new RuntimeException("需要手动为请求信息鉴权"); } if (!EmoneyClient.loginWithManaged()) { throw new RuntimeException("鉴权登录失败"); } } else if (!EmoneyClient.relogin()) { throw new RuntimeException("检查重鉴权失败"); } return pjp.proceed(); } /** * 在方法上添加此注解,则进入该方法前先校验 defaultRequestInfo 已鉴权、代理已配置,否则不允许进入方法 *

需要开启 AOP:在任意配置类上增加注解:@EnableAspectJAutoProxy * @see RequireAuthAndProxyAspect */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public static @interface RequireAuthAndProxy { /** * 当存在默认请求配置但未鉴权时,是否自动鉴权 * @return */ boolean autoLogin() default false; } }