Custom HTML Login Form in HTTP Basic Auth

I have an API with HTTP Basic Auth. If non-authenticated users send HTTP requests, the server returns a 401 status code and a header WWW-Authenticate. And the browser shows a standard login form. Can I display my Google login form instead of the standard browser login form?

+4
source share
1 answer

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) {
       // we are not authenticated => we must redirect the user to our custom login form
       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='
    }
})...
+4
source

Source: https://habr.com/ru/post/1622892/


All Articles