Koajs-authentication

提供:Dev Guides
移動先:案内検索

Koa.js-認証

認証は、提供された資格情報が、ローカルオペレーティングシステムまたは認証サーバー内の承認されたユーザーの情報のデータベースにあるファイルの資格情報と比較されるプロセスです。 資格情報が一致する場合、プロセスは完了し、ユーザーにはアクセスの許可が付与されます。

*Basic HTTP Authentication* を使用する非常に基本的な認証システムを作成します。 これは、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://localhost: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://localhost: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ルートは誰でも引き続きアクセスできます。