* 准备
我们可以访问 github docs 根据文档提示完成github 授权 app的创建
* 注册 、 登录 github.com (需要vpn)
*user - settings
*Developer settings
*New GitHub App (有时候可能需要验证github密码)
*创建应用
创建应用图解
实现步棸
前端实现直接访问github 授权接口,由于同源策略的限制,我们通过服务端代码完成数据请求
~ 前端跳转第三方登录, 登录成功后跳转页面, url获取code码
可以已我下面这个为例
服务端代码
app/router.js
module.exports = (app) => {
const { router, controller } = app;
router.post("/user/accesscode", controller.user.accesscode);
router.get("/user/userinfoByToken", controller.user.userinfoByToken);
};
app/controller/user.js
const { Controller } = require("egg");
const axios = require("axios");
const qs = require("qs");
class UserController extends Controller {
async userinfoByToken() {
console.log(this.ctx.request.query.access_token);
const option = {
url: "https://api.github.com/user",
method: "GET",
headers: {
Authorization: `token ${this.ctx.request.query.access_token}`,
},
};
const result = await axios(option);
if (result.status == 200) {
this.ctx.status = 200;
this.ctx.body = {
code: 1,
result: result.data,
};
} else {
this.ctx.status = 401;
this.ctx.body = {
code: 0,
msg: "参数有误,请重新登录!",
};
}
}
async accesscode() {
const option = {
url: "https://github.com/login/oauth/access_token",
method: "POST",
headers: {
// accept: "application/json",
"content-type": "application/x-www-form-urlencoded",
},
data: qs.stringify({
client_id: "Iv1.86b5d6c018a3665d",
client_secret: "77e78e15d77672135a5ea426d354c33f034baa07",
code: this.ctx.request.body.code,
}),
};
const result = await axios(option);
const info = qs.parse(result.data);
if (result.status === 200) {
this.ctx.body = {
code: 1,
info,
};
}
}
}
module.exports = UserController;
客户端代码
<a href="https://github.com/login/oauth/authorize?client_id=Iv1.86b5d6c018a3665d&redirect_uri=http://localhost:8080">第三方登录</a>
<template>
<div>this is home page{{ authCode }}</div>
</template>
<script>
import { _get_access_token, _getUserInfoByAccessToken } from "@/api/user";
export default {
name: "Home",
async mounted() {
await this.get_access_token();
if (!this.$route.query.code) {
await this.$store.dispatch({ type: "USER_INFO" });
await this.$store.dispatch({ type: "USER_AUTH" });
await this.$store.dispatch({ type: "GET_VIEWS_AUTHORITY" });
}
},
computed: {
authCode() {
return this.$route.query.code;
},
},
methods: {
// 第三方登录,通过code获得access_token
async get_access_token() {
const result = await _get_access_token(this.authCode);
if (result.data.info.access_token) {
// 通过access_token 获取用户信息
const userinfo = await _getUserInfoByAccessToken(
result.data.info.access_token
);
// 更新vuex用户信息
this.$store.commit({
type: "UPDATE_USERINFO",
payload: {
avatar: userinfo.data.result.avatar_url,
username: userinfo.data.result.name,
},
});
// 更新vuex身份令牌,路由请求拦截token可能会一直跳转登录页
this.$store.commit({
type: "UPDATE_TOKEN",
payload: result.data.info.access_token,
});
}
},
},
};
</script>
<style></style>