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

Ild*_*dar 6 javascript http-authentication basic-authentication

我有一个HTTP Basic Auth的API.如果未经过身份验证的用户发送HTTP请求,则服务器将返回401状态代码和WWW-Authenticate标头.浏览器显示标准登录表单.是否可以显示我的HTML登录表单而不是标准浏览器的登录表单?

Dar*_*rov 5

由于您使用的是 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';
   }
});
Run Code Online (Sandbox Code Playgroud)

收集用户名和密码后,您将知道如何在对 API 的后续请求中构建正确的身份验证标头:

$.ajax({
    url: 'https://httpbin.org/basic-auth/user/passwd',
    type: 'GET',
    headers: {
        Authorization: 'Basic dXNlcjpwYXNzd2Q='
    }
})...
Run Code Online (Sandbox Code Playgroud)