KoaJS教程

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.
/unprotected 路由仍然可供所有人访问。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4