實現效果
啓用受權服務器
@Configuration
@EnableAuthorizationServer
public 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...git