Configure CORS on a PHP page with Basic Athenticate

Asked

Viewed 3,166 times

1

I posted the page php test. in the field: https://www.teste.com/api/teste.php

<?php
    header("Access-Control-Allow-Origin: *");
    header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
    header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
if (!(isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) 
    && $_SERVER['PHP_AUTH_USER'] == 'myuser' 
    && $_SERVER['PHP_AUTH_PW'] == 'mypswd')) {

    header('WWW-Authenticate: Basic realm="Restricted area"');
    header('HTTP/1.1 401 Unauthorized');
    $data['result'] = 'HTTP/1.1 401 Unauthorized';
}
else
{
    $data['result'] = 'HTTP/1.1 200 Ok';
}

echo json_encode($data);

?>

And created a page html test. with the call to said API

<html>
    <body>
        <span id="result"></span>
        <a id="btn-post" href="#">POST</a>
    </body>
</html>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
function log(varLog) {

        console.log(varLog);

}
$('#btn-post').click(function () {

$.ajax({
    xhrFields: {
        withCredentials: true
    },
            dataType: 'json',
            type: "post", //Método de envio
            url: 'https://www.teste.com/api/teste.php',
            data: {
                teste:'teste'
            },
            headers: {
                'Authorization': 'Basic ' + btoa('myuser:mypswd')
            },
            beforeSend: function (xhr) { //ocorre antes do POST
                log('beforeSend');      
            },
            success: function (result) { //Sucesso no AJAX  
                log('success');         
                log(result);

            }, 
            error: function(XMLHttpRequest, textStatus, errorThrown) { 
                log('error');
                //log(XMLHttpRequest);
                //log(textStatus);
                //log(errorThrown);

            },
            complete: function (jqXHR, textStatus) { //ocorre ao completar o POST
                log('complete');
                //log(jqXHR);
                //log(textStatus);

            }
        }).done(function (data) {
            log('done');
            //log(data);    
        });

});
</script>

See that in the archive php test. I set the header with Access-Control-Allow-Origin and from what I understand, this would allow the call in different domains and even allow if I don’t use the Basic Authenticate, but with basic authentication CORS does not work at all.

ERRO

1 answer

0

You need to add in the answer, the headers that release the CORS.

Adding the headers in the test.php file, it should look like this:

<?php
    // CORS HEADERS
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");

    header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
    header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

if (!(isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) 
    && $_SERVER['PHP_AUTH_USER'] == 'myuser' 
    && $_SERVER['PHP_AUTH_PW'] == 'mypswd')) {

    header('WWW-Authenticate: Basic realm="Restricted area"');
    header('HTTP/1.1 401 Unauthorized');

    $data['result'] = 'HTTP/1.1 401 Unauthorized';
} else {
    $data['result'] = 'HTTP/1.1 200 Ok';
}

echo json_encode($data);
  • 1

    Thank you for your contribution, but it hasn’t worked yet. Searching more about it I got information that when Basic Authenticate is used it is necessary to make it clear which domain is the source, that is: It is not allowed to use the instruction "Access-Control-Allow-Origin: *" would have to be something like "Access-Control-Allow-Origin: http://localhost". But I still can’t make it work.

  • 2

    Hnm... got it.. I’m sorry it didn’t work. You can send a print of the bug that persists ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.