目录

Koa.js - 身份验证( Authentication)

身份验证是将提供的凭据与本地操作系统或身份验证服务器中授权用户信息的数据库中的凭据进行比较的过程。 如果凭据匹配,则完成该过程并授予用户访问权限。

我们将创建一个非常基本的身份验证系统,它将使用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.

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

↑回到顶部↑
WIKI教程 @2018