I am trying to create a basic authentication through the browser, but I can't really get there.
If this script won't be here the browser authentication will take over, but I want to tell the browser that the user is about to make the authentication.
The address should be something like:
http://username:password@server.in.local/
I have a form:
<form name="cookieform" id="login" method="post">
<input type="text" name="username" id="username" class="text"/>
<input type="password" name="password" id="password" class="text"/>
<input type="submit" name="sub" value="Submit" class="page"/>
</form>
And a script:
var username = $("input#username").val();
var password = $("input#password").val();
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = Base64.encode(tok);
return "Basic " + hash;
}
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
async: false,
data: '{"username": "' + username + '", "password" : "' + password + '"}',
success: function (){
alert('Thanks for your comment!');
}
});
As others have suggested, you can set the username and password directly in the Ajax call:
OR use the headers property if you would rather not store your credentials in plain text:
Whichever way you send it, the server has to be very polite. For Apache, your .htaccess file should look something like this:
Explanation:
For some cross domain requests, the browser sends a preflight OPTIONS request that is missing your authentication headers. Wrap your authentication directives inside the LimitExcept tag to respond properly to the preflight.
Then send a few headers to tell the browser that it is allowed to authenticate, and the Access-Control-Allow-Origin to grant permission for the cross-site request.
In some cases, the * wildcard doesn't work as a value for Access-Control-Allow-Origin: You need to return the exact domain of the callee. Use SetEnvIf to capture this value.
Use the jQuery ajaxSetup function, that can set up default values for all ajax requests.
According to SharkAlley answer it works with nginx too.
I was search for a solution to get data by jQuery from a server behind nginx and restricted by Base Auth. This works for me:
And the JavaScript code is:
Article that I find useful:
There are 3 ways to achieve this as shown below
Method 1:
Method 2:
Method 3:
Use the beforeSend callback to add a HTTP header with the authentication information like so:
JSONP does not work with basic authentication so the jQuery beforeSend callback won't work with JSONP/Script.
I managed to work around this limitation by adding the user and password to the request (e.g. user:pw@domain.tld). This works with pretty much any browser except Internet Explorer where authentication through URLs is not supported (the call will simply not be executed).
See http://support.microsoft.com/kb/834489.