How do I trigger the browser's Basic Authentication dialog from an AJAX call? How do I trigger the browser's Basic Authentication dialog from an AJAX call? ajax ajax

How do I trigger the browser's Basic Authentication dialog from an AJAX call?


Dynamically create an iframe with your url and append to document. It'll trigger authentication form. jQuery snipet to add iframe

$('<iframe src="your_url"></iframe>').appendTo('body')

A very simplified example is here:

var url = 'your_url_here';$.ajax({    url: url,    error: function(response){        if(response.status==401){                       $('<iframe src="'+url+'"></iframe>').appendTo('body');                  }    },    success:function(){        //your success code here    }});


I have faced almost the same 401 problem, except for my request was cross domain. But I hope the reason is the same. Following the instructions on developer.mozilla - Access control CORS I have finally succeeded with simple:

var xhttp=new XMLHttpRequest();xhttp.withCredentials = true;xhttp.open("GET", "https://my.foo.server/app/resource", true);xhttp.send();

I think the xhttp.withCredentials is the solution. It is not header! You let browser to communicate with server through cookies. The following answer explains a lot XHR2 withCredentials - which cookies are sent?

Without xhttp.withCredentials there was always 401 (Unauthorized). But using it, the browser added the required header Authorization:Basic dGVFooFooFooFoosaWVudA== or triggered the login dialog, when credentials were not available yet.