OAuth2 认证基本流程
1、创建应用
2、设置应用主页和回调地址(为服务器可以访问的地址)
3、通过GET请求获取code(这个网址是前端点击跳转的网址)
根据上面创建的应用填入自己的client_id、redirect_uri
https://gitee.com/oauth/authorize?client_id=f1a28c0911ac08c773dc92e57fa3eac7412772bdc6cd07b07fa1a8e51cf97ee9&redirect_uri=http://auth.gulimall.com/oauth2.0/Gitee/success&response_type=code
上面的请求会给回调地址(redirect_uri)传一个code,拿到code后就可以获取access_token
4、获取access_token
@GetMapping(value = "/oauth2.0/Gitee/success")
public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
Map<String, String> map = new HashMap<>();
map.put("client_id","f1a28c0911ac08c773dc92e57fa3eac7412772bdc6cd07b07fa1a8e51cf97ee9");
map.put("client_secret","7bbefbd686d44a6c61b075accab79b335ff1ae3c2b3c270fe1a71c641718ff58");
map.put("grant_type","authorization_code");
map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/Gitee/success");
map.put("code",code);
//1、根据用户授权返回的code换取access_token
HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<>(), map, new HashMap<>());
if (response.getStatusLine().getStatusCode() == 200) {
//获取到了access_token,转为通用社交登录对象
String json = EntityUtils.toString(response.getEntity());
//SocialUser 是根据返回的JSON数据定义的vo,主要用来存储access_token便于其他服务调用
//返回的JSON参考:{
//"access_token": "440f3fbebcd527c322364b0216c06402",
//"token_type": "bearer",
//"expires_in": 86400,
//"refresh_token": "4b1f6b50208a2520278352f399f22129beadbb3ffa58e16b27044d40a09ab7f3",
//"scope": "user_info",
//"created_at": 1719444714}
SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
}
5、调用接口获取Gitee的个人信息(参考官方文档)
Map<String,String> query = new HashMap<>();
query.put("access_token",socialUser.getAccess_token());
HttpResponse response = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<String, String>(), query);
if (response.getStatusLine().getStatusCode() == 200){
String json = EntityUtils.toString(response.getEntity());
JSONObject jsonObject = JSON.parseObject(json);
//获取JSON中的数据
String id = jsonObject.getString("id");