Py学习  »  Git

vue实现GitHub的第三方授权

xuerzong • 4 年前 • 103 次点击  
阅读 24

vue实现GitHub的第三方授权

最近在完善我的博客系统,突然想到从原本临时填写 name + email 进行评论改成使用GitHub授权登陆以发表评论。

废话不多说,直接奔入主题

温馨提示:本文章只满足个人使用需求,如果需要学习更详细的使用方法,可访问 OAuth官方文档

创建OAuth Apps

首先,你需要一个GitHub账户然后前往GitHub developers,根据要求填写完成之后,会自动生成Client_IDClient Secret,在之后的步骤中会用到。

获取code

//method
async githubLogin() {
	windows.location.href = 
    "https://github.com/login/oauth/authorize?client_id = your_client_id&redirect_uri=your_redirect_uri"
}
复制代码
<a href="https://github.com/login/oauth/authorize?client_id = your_client_id&redirect_uri=your_redirect_uri">GitHub登陆</a>
复制代码

路由参数中redirect_uri是可选的。如果省略,则GitHub将重定向到你在OAuth apps配置的回调路径。如果提供,则你所填写的redirect_uri必须是你在OAuth apps中配置的回调路径的子路径。如下:

CALLBACK: http://xx.com/github

GOOD: http://xx.com/github
GOOD: http://xx.com/github/path/path
BAD: http://xx.com/git
BAD: http://xxxxx.com/path
复制代码

如果用户接受你的请求,将会跳转到redirect_uri,我们可以接受路由中的参数code,以进行下一步操作。

your_redirect_uri?code=xxx
复制代码

获取access_token

我们需要client_idclient_secretcode来获取access_token

/*
/githubAccessToken:https://github.com/login/oauth/access_token
*/
this.$axios
	.get('/githubAccessToken',{
	params: {
		client_id: your_client_id,
		client_secret: your_client_secret,
		code: your_code
		}
	})
复制代码

默认情况下,你会获取如下响应:

access_token=xxxxx&token_type=bearer
复制代码

如果你想用更方便的格式接收响应,你可以在headers中自定义Accept

Accept: "application/json"
=> {"access_token":xxxxx,"token_type":bearer}
复制代码

获取用户信息

获取access_token之后,我们就可以请求用户的部分信息了:

/*
/githubUserInfo:https://api.github.com/user
*/
this.$axios
	.get('/githubUserInfo', {
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    Accept: "application/json",
    Authorization: `token ${access_token}` //必填
  }
})
复制代码

然后你便可以获取到用户信息了。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/55023
 
103 次点击