spring boot security oauth2 自定义token返回数据结构

1、前后端,微服务给予security oauth2的认证token 授权

默认返回数据结构是

spring boot security oauth2 自定义token返回数据结构

但是我们希望的时候有统一的返回数据格式

spring boot security oauth2 自定义token返回数据结构

查看源码 可以找到    postAccessToken里面处理的数据返回

所以使用 @Around 注解 拦截请求改变返回值 具体代码如下。

 

@Component
@Aspect
@Slf4j
public class AuthAspectAround {

    @Around("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
    public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
        // 放行
        Result result = new Result();
        Object proceed = pjp.proceed();
        if (proceed != null) {
            ResponseEntity<OAuth2AccessToken> responseEntity = (ResponseEntity<OAuth2AccessToken>)proceed;
            OAuth2AccessToken body = responseEntity.getBody();
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                result =  Result.success(body);
            } else {
                log.error("error:{}", responseEntity.getStatusCode().toString());
                result = Result.fail("授权失败");
            }
        }
        return ResponseEntity
                .status(200)
                .body(result);
    }

}

其中  Result 是自定义的返回数据结构。

当然此改变返回数据结构谨慎使用,比如使用的其他插件使用了security oauth2认证功能,那就不行了。