How to use username and password in ajax header?

Sometimes the access to the requested websites using protection. When you make request call those site will ask credentials to process your request. To accomplish this we have to use Http Authentications. For the XmlHttpRequest (ajax call) we need to set Authorization header to accomplish this protection.

Here we will discuss about How to make ajax request for these type of website using Authorization websites with Basic authentication.

Before that, we should know about Base64 encoding. Because here we will encode our username and password with btoa(Base64-encode text) methos.

Authorization: Basic dGVjaG5pcXpvbmVVc3I6dGVjaG5pcXpvbmVBZG1pbg==


//using jquery beforeSend method
    beforeSend: function (xhr) {
        xhr.setRequestHeader('Authorization', 'Basic ' + btoa('username:password'));
    url: "urlHere"

//using jquery header
    headers: {
        'Authorization' : 'Basic ' + btoa('username:password');
    url: "urlHere"

//using XMLHttpRequest
var xhr = new XMLHttpRequest();"GET", "urlHere", true);
xhr.withCredentials = true;
xhr.setRequestHeader("Authorization", 'Basic ' + btoa('username:password'));
xhr.onload = function () {

In php, you can get these authentication information like below.

	if (!(isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) 
		&& $_SERVER['PHP_AUTH_USER'] == 'username' 
		&& $_SERVER['PHP_AUTH_PW'] == 'password')) {
		header('WWW-Authenticate: Basic realm="Restricted area"');
		header('HTTP/1.1 401 Unauthorized');

Leave a Reply

Your email address will not be published. Required fields are marked *