1,第一步首先需要注册京东云账号获取accessKeyId和secretAccessKey用来创建应用生成clientid
代码
@Test public void test0(){ //申请的accessKeyId和secretAccessKey String accessKeyId = ""; String secretAccessKey = ""; String jdcloudGwUrl = "ias.jdcloud-api.com"; CredentialsProvider staticCredentialsProvider = new StaticCredentialsProvider(accessKeyId, secretAccessKey); Environment env = new Environment.Builder().endpoint(jdcloudGwUrl).build(); IasClient client = IasClient.builder().credentialsProvider(staticCredentialsProvider) .httpRequestConfig(new HttpRequestConfig.Builder().protocol(Protocol.HTTPS).build()) .environment(env) .build(); CreateAppRequest request = new CreateAppRequest(); request.regionId("cn-north-1"); //应用名称自定义 request.setClientName("test"); request.setTokenEndpointAuthMethod("client_secret_post"); //code码的形式进行认证 request.setGrantTypes("authorization_code,refresh_token"); request.setUserType("root"); request.setMultiTenant(true); request.setAccessTokenValiditySeconds(20*60); request.setRefreshTokenValiditySeconds(43200*60); //重定向路径,登录获取code码后,跳转路径 request.setRedirectUris("重定向路径"); request.setScope("openid"); //创建应用的应用密码(建议使用足够复杂的密码) request.setSecret("testsecret"); CreateAppResponse response = client.createApp(request); String result = new Gson().toJson(response); }
返回值结构(只要用clientId)
2,获取clientid后,流程,Authorize Endpoint(将用户跳转到京东云登录获取用户登录授权:会获得一个code码在重定向路径后)——》Token Endpoint(根据code码,获取登录凭证access_token)——》UserInfo Endpoint(根据access_token获取用户京东云的唯一标识account也就是用户京东的唯一用户名)——》最后一步得到唯一标识后可自定义业务逻辑
3,
前端页面发送请求Authorize Endpoint
window.location.href = url + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri + "&response_type=" + response_type +"&code_challenge_method=" + code_challenge_method + "&code_challenge=" + code_challenge + "&state=" + state
Authorize Endpoint发送成功后,后台回调路径代码
@GetMapping("/jdredirect") public ResultInfo<Object> jdRedirect(@RequestParam String code, HttpSession session, HttpServletResponse response) { try { String url = jdConfig.getGateway() + "/token?client_id=" + jdConfig.getClientId() + "&client_secret=" + jdConfig.getClientSecret() + "&grant_type=" + jdConfig.getGrantType() + "&code="; //获取token(Token Endpoint) ResponseEntity<String> codeResponse = restTemplate.getForEntity(url + code, String.class); String access_token = (String) JSON.parseObject(codeResponse.getBody()).get("access_token"); String tokenUrl = jdConfig.getGateway() + "/userinfo"; HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.set("Authorization", "Bearer " + access_token); //获取account唯一标识(UserInfo Endpoint) ResponseEntity<String> tokenResponse = restTemplate.postForEntity(tokenUrl, new HttpEntity<>(httpHeaders), String.class); // String name = (String) JSON.parseObject(tokenResponse.getBody()).get("name"); String name = (String) JSON.parseObject(tokenResponse.getBody()).get("account");
//自定义业务逻辑
}
具体用到时可参考京东api文档