这里利用AOP进行拦截,主要拦截oauth2.0 postAccessToken 这里
@Slf4j
@Component
@Aspect
public class OauthTokenAspect {
@Around("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
public Object handleControllerMethod(ProceedingJoinPoint joinPoint) throws Throwable {
try {
Object[] args = joinPoint.getArgs();
Principal principal = (Principal) args[0];
if (!(principal instanceof Authentication)) {
throw new InsufficientAuthenticationException("未授权成功,请联系管理员");
}
Map<String, String> parameters = (Map<String, String>) args[1];
String grantType = parameters.get(OAuth2Utils.GRANT_TYPE);
Object proceed = joinPoint.proceed();
ResponseEntity<OAuth2AccessToken> responseEntity = (ResponseEntity<OAuth2AccessToken>) proceed;
OAuth2AccessToken body = responseEntity.getBody();
Base baseUser = JsonUtils.toJavaObject(body.getAdditionalInformation().get(Constants.INFO), Base.class);
if (Constants.AUTHORIZATION_CODE.equals(grantType)) {
return proceed;
} else {
TokenVO tokenVO = new TokenVO();
if (!Constants.CLIENT_CREDENTIALS.equals(grantType)) {
//加密
assert body != null;
byte[] b = DesUtils.encrypt(body.getValue().getBytes(), Constants.AES_SECRET);
String str = String.valueOf(b);
//token 加密携带用户信息存入redis
RedisUtils.set(**);
//token 加密信息存入redis
RedisUtils.set(**, 7200);
tokenVO.setAccessToken(str);
} else {
//token 加密信息存入redis
RedisUtils.set(**, baseUser, 7200);
assert body != null;
tokenVO.setAccessToken(body.getValue());
}
tokenVO.setAccountName(baseUser.getAccountName());
tokenVO.setExpiresIn(body.getExpiresIn());
//主要在这里自定义返回内容
return ResponseEntity
.status(HttpStatus.OK)
.body(R.success(tokenVO));
}
} catch (Throwable throwable) {
throw new BusinessException("token 返回异常");
}
}
}