第三方登录——github
前言
第一次接触第三方登录时,一脸懵逼,去哔哩哔哩上查都查不出来,一脸懵逼的我就在百度搜索了这个github第三方登录,相比qq简单点,原理我这里就不在说了,直接上代码,上步骤提示:以下是本篇文章正文内容,下面案例可供参考
一、在github申请第三方应用
第一步
第二步
第三步选择oauth,我这里已经创建一个,创建新的需要点new oauth app
第四步
第一个是网站名:随便填;
第二个是网站地址:你http://localhost:8080也行
第三个是网站介绍:可填可不填,你随意
第四个是回调地址:这个要注意,这个地址是用来接受返回回来的access_token的,你可以在http://localhost:8080/加你前端主页地址(localhost:8080/main)
第五步
点击申请后会给你生成个clientid和clientsecret
二、vue前端操作
第一步:在你需要点击的地方添加点击事件发送post请求,我这里使用的a标签,点击之后,跳入授权页面,授权成功后,回调地址会携带一个code回来
https://github.com/login/oauth/authorize?client_id=你的ClientId&redirect_uri=回调地址
第二步
在mounted钩子函数里面设置获取回调地址携带的code,并将code送给后端
mounted() {
// console.log(window.location.href.indexOf("code=") !==-1);判断是否否找到code=
if(window.location.href.indexOf("code=") == -1){
}else{
var str=window.location.href.substr(window.location.href.indexOf("code=")+5);
// console.log(str);
var Code=str.substr();
console.log(Code);
//后端接口
axios.post('http://127.0.0.1:7001/bpi/login',
{
code:Code,
}).then((res)=>{
console.log(res.data)
}).catch(error=>{
alert("请求超时")
console.log(error)
// this.$router.push("/")
})
}
// return Code;
},
第三步,前端这部分已经结束了
三、后端使用egg.js,它是一个node.js的一个框架,是基于koa。
class LoginController extends Controller {
async GetLogin() {
const axios=require("axios"
const { ctx } = this;
const githubClientSecret="f77ebd62435fb09c7d89ffbe49c7ab9ea53bba90"
const githubClientId="44fdf0c5bd1776fe9a84"
//得到前端post过来的code
const code=ctx.request.body.code;
console.log(ctx.request);
console.log(code)
if(code && code.length==20){
//向github发送post请求,成功的话会,res里面有一个access_token
var res=await axios({
method: 'post',
url:
'http://github.com/login/oauth/access_token?redirect_uri=http://localhost:8080/ToLogin/MobileLogin&' +
`client_id=${githubClientId}&` +
`client_secret=${githubClientSecret}&` +
`code=${code}`,
headers: {
accept: 'application/json',
},
})
// console.log(res.data.access_token)
//拿到res.data.access_token,再向github发送get请求用户信息
var userinfo=await axios({
method: 'get',
url: `https://api.github.com/user?access_token=${res.data.access_token}`,
headers: {
accept: 'application/json',
//这是个坑,一定要这么写,要不然请求不到
Authorization: `token ${res.data.access_token}`,
"Keep-Alive":"timeout=5"
}
})
console.log(userinfo)
}
}
}
module.exports = LoginController;
userinfo里面就是你的github的信息《完》