Github
第三方登录实现获取用户信息
接上一版:https://blog.csdn.net/qq_43516238/article/details/105884926
看这版前先看上一版
步骤一:
前端按钮点击方法
这边有所改变:回调地址去掉了login,因为实际项目中/login容易被拦截器拦截
login() {
const authorize_uri = 'https://github.com/login/oauth/authorize'
const client_id = '029605ac4b8d64a69874'
const redirect_url = 'http://localhost:8080/oauth2/code/github'
// alert('click')
window.location.href = `${authorize_uri}?client_id=${client_id}&redirect_url=${redirect_url}`
}
步骤二:
后端AuthController
接口类
package com.soft1851.music.admin.controller;
import com.alibaba.fastjson.JSONObject;
import com.soft1851.music.admin.annotation.ControllerWebLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping(value = "/oauth2/code/github")
@Slf4j
public class AuthController {
@GetMapping()
@ControllerWebLog
public void getUser(@RequestParam("code") String code) { //这边code必须要加
String token = "";
String user = "";
try {
//创建一个HttpClient对象
HttpClient client = HttpClients.createDefault();
//创建一个Post对象
HttpPost post = new HttpPost("https://github.com/login/oauth/access_token");
//创建一个entity模拟一个表单
List<NameValuePair> list = new ArrayList<>();
list.add(new BasicNameValuePair("client_id", "02**********74"));
list.add(new BasicNameValuePair("client_secret", "7744***********5b0a4"));
list.add(new BasicNameValuePair("code", code));
//包装成一个entity对象
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "UTF-8");
//设置请求内容
post.setEntity(urlEncodedFormEntity);
post.addHeader("accept", "application/json");
post.addHeader("user-agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Mobile Safari/537.36");
//执行请求内容
HttpResponse httpResponse = client.execute(post);
int statusCode = httpResponse.getStatusLine().getStatusCode();
log.info(String.valueOf(statusCode));
HttpEntity contentEntity = httpResponse.getEntity();
String content = EntityUtils.toString(contentEntity);
log.info(content);
token = JSONObject.parseObject(content).getString("access_token");
log.info("token>>>>>>>>>>>>>>>>" + token);
//取user
RequestConfig requestConfig = RequestConfig.custom()
.setExpectContinueEnabled(true)
.setSocketTimeout(10000)
.setConnectTimeout(10000)
.setConnectionRequestTimeout(10000)
.build();
HttpGet get = new HttpGet("https://api.github.com/user?access_token=" + token);
get.setConfig(requestConfig);
get.setHeader("Authorization", "token " + token);
get.setHeader("user-agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Mobile Safari/537.36");
httpResponse = client.execute(get);
contentEntity = httpResponse.getEntity();
user = EntityUtils.toString(contentEntity);
log.info("user>>>>>>>>>>>>" + user);
EntityUtils.consume(contentEntity);
//重定向跳回客户端
ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
assert sra != null;
HttpServletResponse response = sra.getResponse();
response.sendRedirect("http://localhost:8081/#/auth?user=" + user);
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 这个接口其实也就是你的回调地址
- code参数必须要加,要接住过来的参数
- 最后的
response.sendRedirect("http://localhost:8081/#/auth?user=" + user);
这个地址是为了重定向到你前端的界面,因此你前端需要有/auth
这个路由 - 那么如何获取路由中的user参数呢?
步骤三
在你前端页面的created()中按如下方法获取
created() {
console.log('回调')
let user = this.$route.query.user
if (user) {
console.log(user)
this.user = JSON.parse(user)
localStorage.setItem('token', this.user.id)
localStorage.setItem('user', JSON.stringify(user))
this.$store.commit('setUser', JSON.stringify(user))
}
window.location.href = 'http://localhost:8081/#/dashboard'
},
- 可以将user存储到本地存储中,方便后面的数据获取,当然如果你只是想展示相关信息就不用了
- 最后的
window.location.href = 'http://localhost:8081/#/dashboard'
是为了当你数据存储过后跳到首页,因此这个页面其实是不显示的,只是一个中间过渡的作用
最终效果如下(我只拿了用户名和头像)
谢谢!!!留言交流