I'm using basic authentication to secure a set of WCF web services exposed only inside our corporate network, and I was wondering if there was a way to trigger the browser's credentials dialog to appear from an AJAX call when the web service returns with a 401 error?
Currently my AJAX call receives the 401 as a regular failed request and doesn't prompt the browser to do anything. However, if I take the same URI and copy-paste it into into the browser's URL bar, the returned 401 correctly triggers the Basic Authentication dialog.
Is there any way to get the AJAX callback to tell the browser to pop up that dialog?
This popup is part of the HTTP-Authentication. In order to get it, you need to enable it in your web server. As Wikipedia puts it: When the server wants the user agent to authenticate itself towards the server, it can send a request for authentication.
Ensure that you are using a secure connection when you send REST requests. As the user name and password combination are encoded, but not encrypted, you must use a secure connection (HTTPS) when you use HTTP basic authentication with the REST API.
HTTP basic authentication is a simple challenge and response mechanism with which a server can request authentication information (a user ID and password) from a client. The client passes the authentication information to the server in an Authorization header. The authentication information is in base-64 encoding.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With