Home » Javascript » JS Form based Basic Auth still displays browser credentials window?

JS Form based Basic Auth still displays browser credentials window?

Posted by: admin October 18, 2018 Leave a comment

Questions:

I’m attempting to login with Basic Authentication via a standard web form and js.

The current code seems to authenticate correctly (RE: users trigger the Authenticated alert, and nonusers fail) but the redirect to the secured resource gets the browsers Basic Auth login prompt?

Is there something I’m missing here that will allow the initial authentication via JS to stick so the redirect can bypass the default login prompt?

-Login page is at the root of the same domain.
-The secure page is one dir deeper.

    var username = $("input#username").val();
    var password = $("input#password").val();
    var secureURL = "https://example.com/secure/"

    $.ajax
        ({
        type: "GET",
        url: secureURL,
        headers: {
            "Authorization": "Basic " + btoa(username + ":" + password)
        }
        })
        .done(function(){
            alert('Authenticated!')
            window.location.href = secureURL;
        })
        .fail(function(){
            alert('Error!')
        });
    });

Edit:
I think I got it. This is the ajax request body that seems to work as expected.

$.ajax(
    {
      'password' : password,
      'username' : username,
      'url'      : secureURL,
      'type'     : 'GET',
      'success'  : function(){ window.location = secureURL; },
      'error'    : function(){ alert('Bad Login Details');},
    }
  );

  return false;
Answers: