HTTP Basic Auth中的自定义HTML登录表单 [英] Custom HTML login form in HTTP Basic Auth

查看:806
本文介绍了HTTP Basic Auth中的自定义HTML登录表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an API with HTTP Basic Auth. If non-authenticated users send HTTP requests, then the server returns 401 status code and WWW-Authenticate header. And browser shows standard login form. Is it possible to show my HTML login form instead of standard browser's login form?

推荐答案

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

Since you are using an AJAX call, you could intercept the 401 status code from the server and redirect the user to a custom login form. For example let's suppose that you were using jQuery and trying to access the protected with Basic Authentication API endpoint 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:

Once you have collected the username and password you will know how to construct the correct authentication header on subsequent requests to your API:

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

这篇关于HTTP Basic Auth中的自定义HTML登录表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆