1. 程式人生 > >基於nodejs的oauth2實現以及原始碼參考

基於nodejs的oauth2實現以及原始碼參考

通過nodejs伺服器實現一整套oauth2的基本框架

依賴包

npm install oauth2-server@2.4.1

oauth2 結構

|        ├──oauth2              // 主目錄
|             ├──controller     // 控制器
|             ├──model          // 資料庫模型
|             ├──scripts        // 新增指令碼
|             ├──middleware     // 用於routes的中介軟體
|             ├──model          // 用於oauth2的模型           

oauth2 嵌入

中介軟體驗證

router.all('/openapi', oauthMiddleware.oauthDoor, fooCtrl.Foo)

獲取 access_token

router.all('/oauth/access_token', oauthMiddleware.getAccessToken)

一.【模式1】 AppId、AppSecret (Client模式)

1.[匯入Client]

方式1 使用指令碼匯入

node ./backend/oauth2/scripts/importnew

可以配置 AppId、AppSecret, 然後執行指令碼完成匯入新的第三方App

方式2 通過Api介面新增

api 介面: ‘/oauth/client/add’

請求方式1

body: {
    clientId: String
}

將儲存client名稱為指定名稱,方便第三方應用記憶

請求方式2

body: {}

將自動生成 sha1 雜湊

2.申請access_token

申請介面: /oauth/access_token

引數表:

const reqExample = {
    method: 'POST',
    Headers: {
        'Content-Type': "application/x-www-form-urlencoded"
}, body: { grant_type: 'client_credentials', client_id: 'shinepans', // importnew scripts example client_secret: '123' // simple password in test in importnew scripts } }

請求成功後,伺服器將返回:

return example = {
    "token_type": "bearer",
    "access_token": "e5cde9fbeef278b3eebcf55b3ac125589958446a",
    "expires_in": 3600,
    "refresh_token": "c47147ab573e478ed69318690cdd64da04a40790"
}

3.通過得到的access_token訪問api

請求介面例項:

‘/openapi/subjects’

請求引數:

const reqExample = {
    Headers: {
        "Authorization": "Bearer ad77e2040461b23ad2624e9e31076fb92f39ad39"
    }
}

返回結果示例:

return example = {
    "err": 0,
    "data": []
}

關於認證模式

當前使用Clinet認證方式,oauth2支援4中認證模式,當前已實現,模擬微信的oauth2,即通過code獲取access_token以及第三方登入,已有方案,如需開發,可給我留言,我們一起討論。

關於程式碼

程式碼是從實際專案中剝離出來,如果需要嵌入或執行,請仔細審閱程式碼,需要的改動非常小,甚至不需要改動,歡迎使用oauth2參考程式碼。

關於測試

當前剝離專案暫沒有寫任何測試,您可以先通過 postman等工具進行測試,或通過寫指令碼提交http請求來測試。

關於程式碼源參考庫