大致流程
1.先在github中注册的app,获取ClientId和ClientSecret
2.有了开发者的ClientId和ClientSecret后,重定向到:https://github.com/login/oauth/authorize?client_id=" + client_id
@RequestMapping("")
public String login() {
System.out.println(client_id);
return "redirect:https://github.com/login/oauth/authorize?client_id=" + client_id;
}
3.此时会有一个授权页面,如果用户同意授权之后,链接地址就会跳转到我们之前注册app时填的callback的url.并会带上一个code
4.在callback中发送post请求获取AccessToken,然后根据AccessToken来获取用户信息
callback
@RequestMapping("/callback")
@ResponseBody
public Object callback(@RequestParam("code") String code) {
System.out.println(code);
String url = "https://github.com/login/oauth/access_token";
String accessToken = loginService.getAccessToken(url, code, client_id, client_secret);
System.out.println(accessToken);
// return accessToken;
String url2 = "https://api.github.com/user?access_token=";
String token = accessToken.split("&")[0].split("=")[1];
System.out.println(token);
Object userInfo = loginService.getUserInfo(url2+token);
return userInfo;
}
LoginService
public class LoginService {
public static final MediaType MEDIA_TYPE
= MediaType.get("application/json; charset=utf-8");
public String getAccessToken(String url,String code,String client_id,String client_secret) {
HashMap<String, String> map = new HashMap<>();
map.put("code", code);
map.put("client_id", client_id);
map.put("client_secret", client_secret);
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(MEDIA_TYPE, JSON.toJSONString(map));
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public String getUserInfo(String url){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}