Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom HTML login form in HTTP Basic Auth

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?

like image 818
Ildar Avatar asked Jan 05 '16 10:01

Ildar


1 Answers

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='
    }
})...
like image 76
Darin Dimitrov Avatar answered Oct 20 '22 20:10

Darin Dimitrov