首页 > 解决方案 > 如何将 webform 登录添加到 nginx 基本身份验证网站?

问题描述

我有一个带有基本身份验证的简单 nginx 静态站点。当有人想访问该站点时,他们会看到提示输入用户名/密码的浏览器模式对话框:

nginx.conf:

server {
  listen 1337;
  server_name _;
  root /app/public;
  location / {
    auth_basic "Protected";
    auth_basic_user_file /app/etc/htpasswd;
  }
}

如何更改它,而不是对话框,我最终得到一个 Web 表单来针对同一htpasswd文件输入用户名和密码?

我尝试将以下内容添加到nginx.conf

# In location / block
error_page 401 =418 /login/?dest=https://$http_host$request_uri;

# In server block
location /login/ {
  auth_basic off;
}

返回代码418以终止弹出窗口,我喜欢茶壶。在/app/public/login/我创建index.html的有一个简单的形式:

<script>
function authenticate() {
  var login = document.getElementById('username').value;
  var pass = document.getElementById('password').value;
  var xhr = new XMLHttpRequest();
  xhr.withCredentials = true;
  xhr.open("GET", "/", true);
  xhr.setRequestHeader("Authorization", 'Basic ' + btoa(login + ':' + pass));
  xhr.onreadystatechange = function() {
    console.log('xhr ready state: ' + xhr.readyState);
    console.log('xhr status: ' + xhr.status);
    console.log('xhr response: ' + xhr.response);
  };
  xhr.send();
}
</script>
<form method="get" onsubmit="authenticate(); return false">
    <input type="text" id="username" autocomplete="username" required/>
    <input type="password" id="password" autocomplete="current-password" required/>
    <input type="submit" value="OK" />
</form>

我尝试了对原始目标 url 的 AJAX/XHR 以查看它是否返回 200(登录成功)或 418(登录失败),但我无法弄清楚如何在所有后续请求上设置 Authorization 标头,或者是否有可能。任何帮助/建议表示赞赏。

标签: nginxbasic-authentication

解决方案


推荐阅读