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==

Example

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

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

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

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

<?php
	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');
		exit;
	}
?>

Leave a Reply

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