自定义Oauth2.0返回值、及异常处理格式切面类

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springblade.core.tool.api.R;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@Aspect
public class AuthTokenAspect {
/// @Around是可以改变controller返回值的
@Around("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
// 放行
try {
Object proceed = pjp.proceed();
if (proceed != null) {
ResponseEntity responseEntity = (ResponseEntity) proceed;
OAuth2AccessToken body = responseEntity.getBody();
if (responseEntity.getStatusCode().is2xxSuccessful()) {
return new ResponseEntity(R.data(body), HttpStatus.OK);
} else {
log.error("error:{}", responseEntity.getStatusCode().toString());
return new ResponseEntity(R.fail("获取授权码失败"), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
return new ResponseEntity(R.fail("获取授权码失败"), HttpStatus.INTERNAL_SERVER_ERROR);
} catch (Exception e) {
return new ResponseEntity(R.fail(e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
备注:R类是统一返回格式工具类、换成自己的即可.

原文地址:https://www.cnblogs.com/LoveShare/p/14431665.html