(一)HTTPAuth: Node.js 使用 Koa 的 HTTP BasicAuth 基本认证

news/2024/6/16 18:58:54

要点:

  • 不要通过 form 提交表单的默认方式发送请求,转而使用 fetch 或 ajax
  • 客户端注意设置 Authorization 字段的值为 'Basic xxx',通过该 Http 字段传递用户名密码
  • base64 的方法在客户端要注意兼容性 btoa ,建议使用现成的库如 'js-base64' 等,NodeJS 方面使用全局的 Buffer
  • 服务端验证失败后,注意返回 401,但不用返回 'WWW-Authenticate: Basic realm="..."' 避免浏览器出现弹窗
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>AMD</title>
</head>

<body>
  <script defer async="true" src="js/require.js" data-main="js/main"></script>
  <!-- BasicAuth -->
  <div>
    <form id="form" action="">
      <input type="text" name="username" id="username">
      <input type="password" name="password" id="password">
      <button id="login">login</button>
    </form>
  </div>
</body>

</html>
require.config({
  baseUrl: 'js/libs',
  paths: {
    'zepto': 'zepto.min',
  },
  shim: {
    'zepto': 'zepto',
  }
});

define(['zepto'], function ($) {
  let $form = $('#form')
  $form.on('submit', (e) => {
    e.preventDefault()
    $.ajax({
      // ajax 发送验证请求
      type: 'POST',
      url: '/login',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': 'Basic ' + btoa($('#username').val() + ':' + $('#password').val()),
        // 通过 Authorization 传递 base64 编码后的用户名密码
      },
      success: function (data) {
        console.dir(data) // 回调
      }
    })
  })
});
const Koa = require('koa')
const static = require('koa-static')
const router = require('koa-better-router')().loadMethods()
const koaBody = require('koa-body')

const app = new Koa()
app.use(koaBody())
app.use(router.middleware())
app.use(static('public'))
app.listen(8080)

router.post('/login', (ctx, next) => {
  // 省略从数据库中提取用户密码
  if (ctx.get('Authorization') === 'Basic ' + Buffer('fdsa:fdsa').toString('base64')) {
    // 获取 Authorization 字段 比对 base64 用户名密码
    ctx.body = 'secret'
    ctx.type = 'text/html'
    ctx.status = 200 // 匹配成功
  } else {
    ctx.status = 401 // 匹配失败
  }
  next()
})

http://www.niftyadmin.cn/n/4608932.html

相关文章

练习:求1+2+3+4+5...100的和

题目&#xff1a;求12345...100的和方法一 count 1 s1 0 while count < 100: s1 s1 countprint(s1)count 1输出结果&#xff1a; 1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136 153 171 190 210 231 253 276 300 325 351 378 406 435 …

Linux----进程概念(下)

进程概念&#xff08;下&#xff09;7. 环境变量①概念②Linux常见的环境变量1.PATH2.HOME3.SHELL4.HISTSIZE③其他1.环境变量的函数2.本地变量和export3.set和env4.内建命令5.环境变量组织方式以及如何获取环境变量8. 命令行参数9. 初识进程地址空间 &#xff08;重点&#xf…

C++初阶---array forward_list 模板进阶

array forward_list 模板进阶1&#xff09;arrary2&#xff09;forward_list3&#xff09;模板的特化1.函数模板特化2.类模板特化①全特化②偏特化4&#xff09;模板分离编译①分离编译②函数模板分离编译③类模板其他问题5&#xff09;模板总结1&#xff09;arrary 静态数组 注…

Expo大作战(二十三)--expo中expo kit 高级属性(没干货)

简要&#xff1a;本系列文章讲会对expo进行全面的介绍&#xff0c;本人从2017年6月份接触expo以来&#xff0c;对expo的研究断断续续&#xff0c;一路走来将近10个月&#xff0c;废话不多说&#xff0c;接下来你看到内容&#xff0c;讲全部来与官网 我猜去全部机翻个人修改补充…

bzoj1036: [ZJOI2008]树的统计Count link-cut-tree版

题目传送门 这 算是link-cut-tree裸题啊 不过以前好像没有写过单点修改.............. #include<cstdio> #include<cstring> #include<algorithm> #define LL long long using namespace std; const int M50007; int read(){int ans0,f1,cgetchar();while(c&…

【吴恩达】prompt engineering(原则 迭代 文本概括 推断、订餐机器人)

简介 Introduction 基础的LLM训练的模型&#xff0c;问法国的首都什么&#xff0c;可能会将答案预测为“法国最大的城市是什么&#xff0c;法国的人口是多少”许多 LLMs 的研究和实践的动力正在指令调整的 LLMs 上。指令调整的 LLMs 已经被训练来遵循指令。因此&#xff0c;如…

Linux----进程控制(上)

Linux----进程控制&#xff08;上&#xff09;1&#xff09;进程创建fork()① fork()返回值为什么有两个&#xff08;返回两次&#xff09;&#xff1f;② fork()常见使用场景③ fork()调用失败的原因2&#xff09;进程终止进程退出的情况分类进程退出方法①exit()②_exit()在操…

14.Nginx防盗链Nginx访问控制Nginx解析php相关配置Nginx代理

[toc] 一、Nginx防盗链&#xff1a; 1. 打开配置文件&#xff1a; 增加如下配置文件&#xff1a; [rootxavi ~]# cd /usr/local/nginx/conf/vhost/ [rootxavi vhost]# vim test.com.conf} # location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$# {# expires 7d;# …