我有一个带有 HTTP 基本身份验证的 API。如果未经身份验证的用户发送 HTTP 请求,则服务器返回 401 状态码并WWW-Authenticate
标头。浏览器显示标准登录表单。是否可以显示我的 HTML 登录表单而不是标准浏览器的登录表单?
由于您使用的是 AJAX 调用,因此您可以拦截来自服务器的 401 状态代码并将用户重定向到自定义登录表单。例如,假设您正在使用 jQuery 并尝试访问受基本身份验证 API 端点保护https://httpbin.org/basic-auth/user/passwd 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 的后续请求中构造正确的身份验证标头:
$.ajax({
url: 'https://httpbin.org/basic-auth/user/passwd',
type: 'GET',
headers: {
Authorization: 'Basic dXNlcjpwYXNzd2Q='
}
})...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)