Custom HTML login form in HTTP Basic Auth

笑着哭i 提交于 2019-12-08 21:00:52

问题


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?


回答1:


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';
   }
});

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='
    }
})...


来源:https://stackoverflow.com/questions/34609521/custom-html-login-form-in-http-basic-auth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!