Search code examples
javascripthttp-authenticationbasic-authentication

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?


Solution

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