上一篇文章《实战Spring Cloud Oauth2系列(六)统一异常返回结果》我们介绍了使用spring security oauth2.0的时候遇到异常,我们把异常的格式转换成统一格式,但是还有一个问题,由于这个oauth里面的接口不是我们写的,那么此时返回成功的数据格式它也不是我们想要的,看下图:
这里返回的格式是:
{ "access_token": "0917d869-a856-44df-8cd9-bf5116dc5bbf", "token_type": "bearer", "refresh_token": "ad6a4b37-1141-44d5-b770-c73cb8ee203f", "expires_in": 7014, "scope": "all" }
但是我们期望的格式是:
{ "errorCode": 200, "errorMsg": "请求成功", "data": { "access_token": "0917d869-a856-44df-8cd9-bf5116dc5bbf", "token_type": "bearer", "refresh_token": "ad6a4b37-1141-44d5-b770-c73cb8ee203f", "expires_in": 7014, "scope": "all" } }
所以这里的话,我们怎么办呢?其实就是重写一个这个接口,按照oauth的逻辑来调用对应的方法即可。
这里我们其他的地方不做改动,新创建一个controller,完整代码如下:
package org.shop.oauth.server.controller; import java.security.Principal; import java.util.Map; import org.shop.common.model.http.BaseResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import lombok.extern.slf4j.Slf4j; @RestController @RequestMapping("/oauth") @Slf4j public class OauthController { // 令牌请求的端点 @Autowired private TokenEndpoint tokenEndpoint; /** * 重写/oauth/token这个默认接口,返回的数据格式统一 */ @PostMapping(value = "/token") public BaseResponse postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException { OAuth2AccessToken accessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody(); return BaseResponse.ok(accessToken); } }
可以看到我们重写了/oauth/token接口,然后对结果进行了包装,按照正常的流程,请求/oauth/token整个接口的时候,他会自动引导到我们的项目里面这个oauthController里面来。有个这个controller之后,我们把项目启动起来,请求下看看:
可以看到这种格式就是我们想要的格式了。然后我们看看其他的有没有什么问题,看看刷新token的请求结果
也完全没有问题。
最后按照惯例,附上本案例的源码,登录后即可下载
还没有评论,来说两句吧...