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://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.

每个人仍然可以访问/不受保护的路线.