# GitHub授权登录

注意:到2021年5月5日,GitHub不在使用基本身份认证(即使用用户名和密码认证登录),而统一采用OAuth2认证,这里也统一采用此认证方式。

# 授权认证流程

  1. 打开开发配置页面
  2. 创建OAuth应用
  3. 授权OAuth2应用程序

请求用户的GitHub身份,传递一下参数:

  • client_id:在第1步中获取
  • state:自定义,用于判断认证
  • scope作用域参数,指定访问权限,这里指定notifications user repo
  • redirect_uri:用户获得授权后被发送到的应用程序中的URL,详细说明,不指定,默认为创建OAuth2应用时配置的回调地址
```conf
GET https://github.com/login/oauth/authorize
```
  1. 用户授权后将会跳转到回调地址,回调地址中会附带code和state参数

code和state参数可通过一下函数获取






 
 















/**
* 获取href页面参数key
*/
export const getQueryString = key => {
  // 方法一:正则
  var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)")
  var r = window.location.search.substr(1).match(reg)
  if (r != null) return unescape(r[2])
  return null
  
  // 方法二:字符串
  // var url = window.location.search;
  // var theRequest = new Object();
  // if (url.indexOf("?") != -1) {
  // var str = url.substr(1);
  // var strs = str.split("&");
  // for (var i = 0; i < strs.length; i++) {
  //     theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
  //     }
  // }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  1. 获取access_token,请求地址传递参数如下:
POST https://github.com/login/oauth/access_token
1
  • client_id:创建OAuth2应用获取
  • client_secret:创建OAuth2应用获取
  • code:第4步获取的code
  • state:第4步获取的state

结果会返回access_token

access_token=e72e16c7e42f292c6912e7710c838347ae178b4a&token_type=bearer
1
  1. access_token作为令牌添加到头部,访问api,FunCodeapi/api.js中的请求拦截中添加header
Authorization: token OAUTH-TOKEN
1



 




minRequest.interceptors.request((request) => {
  const accessToken = Vue.prototype.$store.getters.accessToken
  if (accessToken) {
    request.header['Authorization'] = `token ${accessToken}`
  }
  return request
})
1
2
3
4
5
6
7

# 注意

跳转认证地址APP和H5平台是不同的

web-view拦截url,获取code和state,创建OAuth2应用时,回调地址要和这里一致,即funcode://oauth

 





wv.overrideUrlLoading({mode: 'reject', match: '^funcode://oauth.*'}, event => {
  const code = getQueryString4Url(event.url, 'code')
  const state = getQueryString4Url(event.url, 'state')
  this.$store.dispatch('authLogin', { code, state })
})
1
2
3
4
5
  • H5平台采用window.location.href,回调地址为http:IP:PORT/funcode/#/pages/login/auth-h5-callback,即auth-h5-callback.vue组件的访问地址

    调试时IPPORT可以改为测试环境,如localhost

兼容APP和H5两种跳转认证

loginAuth() {
  //#ifdef APP-PLUS
  uni.navigateTo({
    url: '/pages/login/auth'
  })
  //#endif
  //#ifdef H5
  window.location.href = globalConfig.githubAuthUrl
  //#endif
}
1
2
3
4
5
6
7
8
9
10
Last Updated: 8/26/2020, 9:02:54 PM