1,创建认证的应用信息
2,填写应用信息
3,创建成功后,从图1位置点击进入
4,主要使用以下三个url
// 跳转到登录认证页面
https://github.com/login/oauth/authorize
// 获取认证成功后的令牌
https://github.com/login/oauth/access_token
// 从令牌获取用户信息
https://api.github.com/user
5,代码实战
配置参数
github:
# 客户端ID
clientId: xxxxxx
# 客户端秘钥
clientSecret: xxxxxxxx
# 用户授权地址(返回授权码)
authorizationUrl: https://github.com/login/oauth/authorize
# 回调地址,获取access_token
redirectUrl: http://localhost:8082/auth2/success
# 认证服务器生成access_token
accessTokenUrl: https://github.com/login/oauth/access_token
# 获取用户身份信息
userInfoUrl: https://api.github.com/user
auth2Properties即为上图的配置信息
// 首先调用此方法,跳转到github认证登录页面
@GetMapping("/oauth/authorize")
public String authorize(){
String url = auth2Properties.getAuthorizationUrl() +
"?client_id="+auth2Properties.getClientId() +
"&redirect_uri="+auth2Properties.getRedirectUrl();
log.info("授权url:{}",url);
// 重定向到授权地址
return "redirect:"+url;
}
// 成功认证后回调方法
@GetMapping("/auth2/success")
public String callback(@RequestParam("code") String code,
Model model,
HttpServletRequest request,
HttpServletResponse response){
// 获取access_token
//https://github.com/login/oauth/access_token?client_id...
// 组装参数
String url = auth2Properties.getAccessTokenUrl()+
"?client_id="+auth2Properties.getClientId()+
"&client_secret="+auth2Properties.getClientSecret()+
"&code="+code+
"&grant_type=authorization_code";
// 以上请求就是获取access_token的请求
log.info("获取access_token请求:{}",url);
// 构建请求头
HttpHeaders headers = new HttpHeaders();
headers.add("accept","application/json");
// 构建请求响应实体对象
HttpEntity<String> httpEntity = new HttpEntity<>(headers);
// post请求方式
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
// 获取请求响应结果
String result = responseEntity.getBody();
//
log.info("远程请求github授权地址,获取access_token:{}",result);
//解析响应结果
Map<String,String> maps = JSON.parseObject(result,Map.class);
// 获取access_token
String access_token = maps.get("access_token");
// 使用access_token换取用户信息,实现用户登录
OAuthUser oAuthUser = this.getUserInfo(access_token);
}
private OAuthUser getUserInfo(String access_token) {
// 获取请求地址
String url = auth2Properties.getUserInfoUrl();
// 构建请求头
HttpHeaders headers = new HttpHeaders();
headers.add("accept","application/json");
// 把access_token放入请求头
headers.add("Authorization","token "+access_token);
// 构建请求响应实体对象
HttpEntity<String> httpEntity = new HttpEntity<>(headers);
// get请求方式
ResponseEntity<String> responseEntity = restTemplate.exchange(url,
HttpMethod.GET,
httpEntity,
String.class);
// 获取请求响应结果
String result = responseEntity.getBody();
// 把json字符串转换为对象
OAuthUser oAuthUser = JSON.parseObject(result, OAuthUser.class);
return oAuthUser;
}