GitHub--oauth驗證登入

AnDongCai發表於2017-09-19

作為一名前端開發學員,必要的後端知識還是要會一些的,最直接的最基礎的就是登入的實現了。這裡就以GitHub為例,首先就是去GitHub官網設定必要的資訊了,過程如下:開啟官網登入自己的賬號:開啟 Setting -> Developer settingGitHub--oauth驗證登入


 -> OAuth applications ->點選 Register a new application ->設定Application name、Homepage URL、Application description、Authorization callback URL。更詳細的過程可參考官方文件。上一段圖吧,更加直觀。如下:

GitHub--oauth驗證登入   GitHub--oauth驗證登入

GitHub--oauth驗證登入GitHub--oauth驗證登入

其中屬於我的個人客戶端資料被擦除了一些,想實現的朋友可以使用自己的;

接下來慢慢實現了,目前來說很多大型網站都支援第三方登入了,作為一個程式設計師上GitHub的頻率算高了,這裡就以GitHub為例。而說到第三方登入,就不得不說到Oauth了,OAuth(開放授權)是一個開放標準,允許使用者讓第三方應用訪問該使用者在某一網站上儲存的私密的資源(如照片,視訊,聯絡人列表),而無需將使用者名稱和密碼提供給第三方應用。這個協議需要客服端提交的資料和服務提供方(GitHub)的資料進行匹配,正確且授權就能通過,其OAuth 協議的登入和授權的過程如下:A、客戶端將使用者導向認證伺服器;B、使用者決定是否給予客戶端授權;C、如果使用者授權,認證伺服器將使用者導向客戶端指定的重定向URI,並在URI的hash部分給出code;D、瀏覽器向資源伺服器發出請求,申請令牌;E、得到令牌 拿著令牌做操作。

上一段程式碼:

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;複製程式碼

其中配置頁程式碼如下:

module.exports = {    
'client_id': '1fc534c9a4*************',    
'client_secret': 'f5380d4*****************aeb2027ac87b6dc6',    
'scope': ['user']  // 授權範圍
}複製程式碼

最後再上一波效果圖:

GitHub--oauth驗證登入 GitHub--oauth驗證登入


GitHub--oauth驗證登入

完整程式碼詳見本人GitHub

其中的流程就是客戶端:提交資料給GitHub進行驗證,驗證通過再繼續授權,申請得到一個令牌,得到令牌就可以做接下的別的操作了,同時令牌超過一段時間,令牌環失效,失效之後需重新更新。

希望這篇文章對大家有所幫助,有什麼意見和想法,也可以在本文底部留言。


相關文章