做爲一名前端開發學員,必要的後端知識仍是要會一些的,最直接的最基礎的就是登陸的實現了。這裏就以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