Koa.js - 身份驗證



身份驗證是一個過程,在這個過程中,提供的憑據與本地作業系統或身份驗證伺服器中授權使用者的資訊資料庫中儲存的憑據進行比較。如果憑據匹配,則該過程完成,並且授予使用者訪問許可權。

我們將建立一個非常基本的身份驗證系統,該系統將使用基本 HTTP 身份驗證。這是實施訪問控制的最簡單方法,因為它不需要 Cookie、會話或任何其他東西。要使用此功能,客戶端必須在其發出的每個請求中傳送 Authorization 標頭。使用者名稱和密碼未加密,而是像下面這樣連線在一個字串中。

username:password

此字串使用 Base64 編碼,並且在該值之前添加了單詞 Basic。例如,如果您的使用者名稱為 Ayush,密碼為 India,則字串“Ayush:India”將作為編碼傳送到授權標頭中。

Authorization: Basic QXl1c2g6SW5kaWE=

要在您的 koa 應用程式中實現此功能,您需要 koa-basic-auth 中介軟體。使用以下命令安裝它:

$ npm install --save koa-basic-auth

現在開啟您的 app.js 檔案並在其中輸入以下程式碼。

//This is what the authentication would be checked against
var credentials = { name: 'Ayush', pass: 'India' }

var koa = require('koa');
var auth = require('koa-basic-auth');
var _ = require('koa-router')();

var app = koa();

//Error handling middleware
app.use(function *(next){
   try {
      yield next;
   } catch (err) {
      if (401 == err.status) {
         this.status = 401;
         this.set('WWW-Authenticate', 'Basic');
         this.body = 'You have no access here';
      } else {
         throw err;
      }
   }
});

// Set up authentication here as first middleware. 
// This returns an error if user is not authenticated.
_.get('/protected', auth(credentials), function *(){
   this.body = 'You have access to the protected area.';
   yield next;
});

// No authentication middleware present here.
_.get('/unprotected', function*(next){
   this.body = "Anyone can access this area";
   yield next;
});

app.use(_.routes());
app.listen(3000);

我們建立了一個錯誤處理中介軟體來處理所有與身份驗證相關的錯誤。然後,我們建立了 2 個路由:

  • /protected - 只有在使用者傳送正確的身份驗證標頭時才能訪問此路由。對於所有其他情況,它將給出錯誤。

  • /unprotected - 任何人都可以訪問此路由,無論是否進行身份驗證。

現在,如果您在沒有身份驗證標頭或使用錯誤的憑據向 /protected 傳送請求,您將收到錯誤。例如:

$ curl https://:3000/protected

您將收到以下響應:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Basic
Content-Type: text/plain; charset=utf-8
Content-Length: 28
Date: Sat, 17 Sep 2016 19:05:56 GMT
Connection: keep-alive

Please authenticate yourself

但是,使用正確的憑據,您將獲得預期的響應。例如:

$ curl -H "Authorization: basic QXl1c2g6SW5kaWE=" https://:3000/protected -i

您將收到以下響應:

HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Content-Length: 38
Date: Sat, 17 Sep 2016 19:07:33 GMT
Connection: keep-alive

You have access to the protected area.

/unprotected 路由仍然可以被所有人訪問。

廣告

© . All rights reserved.