springcloud使用feign和aspect鉴权token
2020-05-14 本文已影响0人
Plator
/**
* UserAuthAspect
*
* @Description 非用户中心用户权限验证
* @Author Plator Lyu
* @Email PlatorDream@gmail.com
* @Date 2020/4/27 14:40
*/
@Aspect
@Component
public class UserAuthAspect {
@Resource
UserLoginFeign userLoginFeign;
@Pointcut("@annotation(cn.plator.feigns.annotation.UserLogin)")
public void userLoginPoint() {
}
@Pointcut("@annotation(cn.plator.feigns.annotation.UserNoLogin)")
public void userNoLoginPoint() {
}
@Around("userLoginPoint() || userNoLoginPoint()")
public Object around(ProceedingJoinPoint point) throws Throwable {
UserNoLogin userNoLogin = ((MethodSignature) point.getSignature()).getMethod().getAnnotation(UserNoLogin.class);
String token = HttpContextUtils.getHttpServletRequest().getParameter(Constant.TOKEN_USER_KEY);
if (StringUtils.isBlank(token)) {
if (userNoLogin != null) {
return point.proceed();
}
throw new ServiceException(HttpStatusCode.TOKEN_EXPIRE.msg, HttpStatusCode.TOKEN_EXPIRE.code);
}
JsonReturn jsonReturn = null;
try {
jsonReturn = userLoginFeign.checkToken(token);
} catch (Exception e) {
if (e.getMessage().contains("Load balancer does not have available server")) {
throw new ServiceException(HttpStatusCode.ERROR_USER_DOWN.msg,HttpStatusCode.ERROR_USER_DOWN.code);
}
}
Integer tokenErrorCode = HttpStatusCode.TOKEN_ERROR.code;
String code = MapUtils.getStrVal(jsonReturn, "code");
if (StringUtils.isBlank(code) || !"0".equals(code)) {
if (userNoLogin == null) {
tokenErrorCode = MapUtils.getIntegerVal(jsonReturn, "code");
}
throw new ServiceException(MapUtils.getStrVal(jsonReturn, "msg"), tokenErrorCode);
}
HttpContextUtils.getHttpServletRequest().setAttribute(Constant.USER_KEY, getUserAndComanyId(jsonReturn));
return point.proceed();
}
@AfterThrowing(throwing = "ex", pointcut = "@annotation(cn.plator.feigns.annotation.UserLogin) || @annotation(cn.plator.feigns.annotation.UserNoLogin)")
private void writeToHttpResponse(Exception ex) {
ServiceException exception = (ServiceException) ex.getCause();
JsonReturn.responseJson(exception.getCode(), exception.getMessage());
}