按照官方文档:
一步一步来,前两步只是创建,主要是第三步:
官网说的很明白:官网步骤
示例代码:
先是客户端发出请求
<a href="https://github.com/login/oauth/authorize?client_id=???&redirect_uri=http://localhost:8081/callback&scope=user&state=1">登录GitHub</a>
client_id是注册时创建的id
地址有个回调接口,在controller写以下方法:
@GetMapping("callback")
public String getCallBack(@RequestParam("code") String code,
@RequestParam("state") String state,
HttpServletRequest request,
HttpServletResponse response) {
AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
accessTokenDTO.setClient_id(clientId);
accessTokenDTO.setClient_secret(client_secret);
accessTokenDTO.setCode(code);
accessTokenDTO.setRedirect_uri(uri);
accessTokenDTO.setState(state);
String accessToken = githubUtil.getAccessToken(accessTokenDTO);
GithubUser githubUser = githubUtil.getUser(accessToken);
if (githubUser!=null){
User user = new User();
user.setAccountId(String.valueOf(githubUser.getId()));
String token = UUID.randomUUID().toString();
user.setToken(token);
user.setName(githubUser.getName());
user.setGmtCreate(System.currentTimeMillis());
user.setGmtModified(user.getGmtCreate());
userMapper.insert(user);
response.addCookie(new Cookie("token",token));
return "redirect:/";
}else {
//登录失败
}
return "/";
}
AccessTokenDTO 实体类,就是注册时的创建的id和client_secret,code是客户端请求后返回的数据:
public class AccessTokenDTO {
private String client_id;
private String client_secret;
private String code;
private String redirect_uri;
private String state;
}
通过code得到token:
public String getAccessToken(AccessTokenDTO accessTokenDTO){
MediaType mediaType = MediaType.get("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(accessTokenDTO));
Request request = new Request.Builder()
.url("https://github.com/login/oauth/access_token")
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
String string = response.body().string();
String accessToken = string.split("&")[0].split("=")[1];
return accessToken;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
通过token得到user信息:
public GithubUser getUser(String accessToken){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://api.github.com/user?access_token="+accessToken)
.build();
try (Response response = client.newCall(request).execute()) {
String string = response.body().string();
GithubUser user = JSON.parseObject(string,GithubUser.class);
return user;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
完整代码:https://github.com/xiaotaogea/github.git
有不明白的可以加下qq哦,相互学习:1213544665