Since you are using an AJAX call, you can intercept the 401 status code from the server and redirect the user to the user login form. For example, suppose you used jQuery and tried to access the secure endpoint of the Basic Authentication 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) {
window.location.href = '/my-custom-login-form';
}
});
After you collect the username and password, you will learn how to build the correct verification header for subsequent requests to your API:
$.ajax({
url: 'https://httpbin.org/basic-auth/user/passwd',
type: 'GET',
headers: {
Authorization: 'Basic dXNlcjpwYXNzd2Q='
}
})...
source
share