做为一名前端开发学员,必要的后端知识仍是要会一些的,最直接的最基础的就是登陆的实现了。这里就以GitHub为例,首先就是去GitHub官网设置必要的信息了,过程以下:打开官网登陆本身的帐号:打开 Setting -> Developer setting前端
-> OAuth applications ->点击 Register a new application ->设置Application name、Homepage URL、Application description、Authorization callback URL。更详细的过程可参考官方文档。上一段图吧,更加直观。以下:node
其中属于个人我的客户端数据被擦除了一些,想实现的朋友可使用本身的;git
接下来慢慢实现了,目前来讲不少大型网站都支持第三方登陆了,做为一个程序员上GitHub的频率算高了,这里就以GitHub为例。而说到第三方登陆,就不得不说到Oauth了,OAuth(开放受权)是一个开放标准,容许用户让第三方应用访问该用户在某一网站上存储的私密的资源(如照片,视频,联系人列表),而无需将用户名和密码提供给第三方应用。这个协议须要客服端提交的数据和服务提供方(GitHub)的数据进行匹配,正确且受权就能经过,其OAuth 协议的登陆和受权的过程以下:A、客户端将用户导向认证服务器;B、用户决定是否给予客户端受权;C、若是用户受权,认证服务器将用户导向客户端指定的重定向URI,并在URI的hash部分给出code;D、浏览器向资源服务器发出请求,申请令牌;E、获得令牌 拿着令牌作操做。程序员
上一段代码:github
const router = require('koa-router')()
const config = require('../config')
const fetch = require('node-fetch')
const routes = router
.get('/login', async (ctx) => {
// 去到github受权页
const dataStr = (new Date()).valueOf();
var path = 'https://github.com/login/oauth/authorize';
path += '?client_id=' + config.client_id;
path += '&scope=' + config.scope;
path += '&state=' + dataStr;
console.log(path)
// authorize 受权 (注册/申请)一下咱们的应用
ctx.redirect(path) // 送到受权的中间页
})
.get('/oauth/callback', async (ctx) => {
const code = ctx.query.code
let path = 'https://github.com/login/oauth/access_token';
const params = {
client_id: config.client_id,
client_secret: config.client_secret,
code: code
}
await fetch(path, {
// 没有fetch,须要装node-fetch
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
})
.then(res => {
// console.log(res)
return res.text() // 得到到的是一个二进制流,转换成文本
})
.then(body => {
const args = body.split('&');
let arg = args[0].split('=');
const access_token = arg[1];
console.log(access_token);
return access_token;
})
.then(async(token) => {
const url =
'https://api.github.com/user?access_token=' + token // token就是oauth令牌环
console.log(url)
await fetch(url)
.then(res => {
return res.json()
})
.then(res => {
console.log(res)
ctx.body = res
})
})
})
module.exports = routes;复制代码
其中配置页代码以下:json
module.exports = {
'client_id': '1fc534c9a4*************',
'client_secret': 'f5380d4*****************aeb2027ac87b6dc6',
'scope': ['user'] // 受权范围
}复制代码
最后再上一波效果图:后端
完整代码详见本人GitHubapi
其中的流程就是客户端:提交数据给GitHub进行验证,验证经过再继续受权,申请获得一个令牌,获得令牌就能够作接下的别的操做了,同时令牌超过一段时间,令牌环失效,失效以后需从新更新。浏览器
但愿这篇文章对你们有所帮助,有什么意见和想法,也能够在本文底部留言。
bash