HTTP Basic Auth 中的自定义 HTML 登录表单

Custom HTML login form in HTTP Basic Auth

我有一个 API 具有 HTTP 基本身份验证。如果non-authenticated用户发送HTTP请求,则服务器returns401状态码和WWW-Authenticateheader。浏览器显示标准登录表单。是否可以显示我的 HTML 登录表单而不是标准浏览器的登录表单?

由于您使用的是 AJAX 调用,您可以拦截来自服务器的 401 状态代码并将用户重定向到自定义登录表单。例如,假设您正在使用 jQuery 并尝试访问受基本身份验证保护的 API 端点 https://httpbin.org/basic-auth/user/passwd:

$.ajax({
    url: 'https://httpbin.org/basic-auth/user/passwd',
    type: 'GET'
}).then(function(result) {
    alert('success');
}).fail(function(xhr) {
   if (xhr.status === 401) {
       // we are not authenticated => we must redirect the user to our custom login form
       window.location.href = '/my-custom-login-form';
   }
});

一旦您收集了用户名和密码,您将知道如何在对您的 API:

的后续请求中构建正确的身份验证 header
$.ajax({
    url: 'https://httpbin.org/basic-auth/user/passwd',
    type: 'GET',
    headers: {
        Authorization: 'Basic dXNlcjpwYXNzd2Q='
    }
})...