网站接入Github登录

891 阅读2分钟
原文链接: blog.animebz.com

给自己的博客加上了Github登录,记录下开发的过程和遇到的一些坑

一、创建Github的开发者应用

这一步首先需要你有Github账号,没有的话就注册一个吧

  1. 登录你的Github账号,进入配置(Settings)

  2. 然后进入开发配置(Developer settings)

  3. 创建OAuth Apps,填写一些必要的信息

二、Web 接入流程

1、重定向到Github,获取用户身份

GET https://github.com/login/oauth/authorize

参数名称 参数类型 说明
client_id string 【必填】创建的应用的Client ID OAuth Apps
redirect_uri string 授权成功之后跳转的地址,可以不填,不填就默认创建应用时填写的返回地址。如果填写,必须和应用里设置的回调地址一样!!
scope string 授权范围 scopes
state string 随机字符串,用于防止跨站点请求伪造攻击(cross-site request forgery attacks)。回调时会带上此参数
allow_signup string 是否提供注册选项,默认true。如果禁止就填false

2、用户登录成功之后,重定向回设置的回调地址

1. 验证 state 防止跨站点请求伪造攻击

2. 获取 access_token

POST请求Github的API,获取access_token

注意:如果这个接口返回404,那可以将 Content-Type 设置成 application/json,并且参数用JSON形式提交!!

POST https://github.com/login/oauth/access_token

参数名称 参数类型 说明
client_id string 【必填】创建的应用的Client ID OAuth Apps
client_secret string 【必填】创建的应用的Client Secret
code string 【必填】第一步返回

默认返回格式:

access_token=e72e16c7e42f292c6912e7710c838347ae178b4a&token_type=bearer

可以在请求头加入 Accept :

Accept: application/json
{"access_token":"e72e16c7e42f292c6912e7710c838347ae178b4a", "scope":"repo,gist", "token_type":"bearer"}

Accept: application/xml
<OAuth>
  <token_type>bearer</token_type>
  <scope>repo,gist</scope>
  <access_token>e72e16c7e42f292c6912e7710c838347ae178b4a</access_token>
</OAuth>

3. 用 access_token 获取用户信息

GET 请求Github的API,获取登录用户信息

注意:调用该API,需要添加 User-Agent 请求头,值为用户名或应用名称,不然一样404!!

GET https://api.github.com/user?access_token=

也可以用加入 Authorization 请求头的方式

curl -H "Authorization: token OAUTH-TOKEN" https://api.github.com/user

参考地址:
Authorizing OAuth Apps
get-the-authenticated-user
user-agent-required