Home » Php » php – Javascript CORS Request with Credentials Fails

php – Javascript CORS Request with Credentials Fails

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am running Apache2 on Debian, I have Javascript (in an Android App) calling a PHP script on my server, it works when credentials are not being used.

Javascript running in an Android App

var encodedUrl = "https://mysite/protected/test.php";

var myHeaders = new Headers();

myHeaders.append('Authorization', 'Basic ' + btoa("myUser:myPass"));

fetch(encodeUrl, {
  mode: "cors",
  method: "get",
  credentials: "include",
  cache: "no-cache",
  headers: myHeaders
})
.then(function(response) {
   response.text().then(function(text){
   alert('success: ' + text);
});
})
.catch(function(err){
  alert('error ' + err);
});

php being called test.php

error_reporting(E_ALL);
ini_set('display_errors', 1);

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: Authorization, X-Requested-With, origin, content-type');
header('Access-Control-Allow-Credentials: true');
header('Cache-Control: no-cache');
header('Pragma: no-cache');
header('Content-Type: text/plain');

print('working!!');

my .htaccess file

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "Authorization, origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "GET"

AuthType Basic
AuthName "???"
AuthUserFile /var/www/mysite/.htpasswd
Require valid-user

The error I get from javascript side

 TypeError: NetworkError when attempting to fetch resource

My apache error logs do not show anything. This script works well when it’s not in a password protected folder.

I have also tried

myHeaders.set

rather than

myHeaders.append

With no difference in outcome

I have also tried passing the credentials in the url directly but that does not work.

Thoughts? Thanks

How to&Answers: