Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use basic authentication with jQuery and Ajax

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:[email protected]/ 

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!');     } }); 
like image 845
Patrioticcow Avatar asked Mar 31 '11 22:03

Patrioticcow


1 Answers

Use jQuery's beforeSend callback to add an HTTP header with the authentication information:

beforeSend: function (xhr) {     xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password)); }, 
like image 189
ggarber Avatar answered Oct 13 '22 08:10

ggarber