实现效果

启用授权服务器

@Configuration@EnableAuthorizationServerpublic class AuthorizationServerConfigurer extends AuthorizationServerConfigurerAdapter {    //......        @Override    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {              endpoints.tokenEnhancer(new TokenEnhancer() {            @Override            public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {            //在此追加返回的数据                DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) oAuth2AccessToken;                CustomUser user = (CustomUser) oAuth2Authentication.getDetails();                Map<String, Object> map = new LinkedHashMap<>();                map.put("nickname", user.getNickname());                map.put("mobile", user.getMobile());                map.put("avatar",user.getAvatar());                token.setAdditionalInformation(map);                return oAuth2AccessToken;            }        });    }    }

创建响应实体

@Data@NoArgsConstructor@AllArgsConstructor@JsonInclude(JsonInclude.Include.NON_NULL)public class Result {    //是否成功    private boolean success;    //返回码    private int code;    //返回信息    private String msg;    //返回数据    private Object data;    public static Result build(Object data) {        return new Result(true, 200, "操作成功",data);    }    }

重写令牌申请接口

@RestController@RequestMapping("/oauth")public class OauthController {    @Autowired    private TokenEndpoint tokenEndpoint;    @GetMapping("/token")    public Result getAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {        return custom(tokenEndpoint.getAccessToken(principal, parameters).getBody());    }    @PostMapping("/token")    public Result postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {        return custom(tokenEndpoint.postAccessToken(principal, parameters).getBody());    }    //自定义返回格式    private Result custom(OAuth2AccessToken accessToken) {        DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) accessToken;        Map<String, Object> data = new LinkedHashMap(token.getAdditionalInformation());        data.put("accessToken", token.getValue());        if (token.getRefreshToken() != null) {            data.put("refreshToken", token.getRefreshToken().getValue());        }        return Result.build(data);    }}

项目源码

https://gitee.com/yugu/demo-o...