skip to Main Content

I’m passing a custom X-Authorization header to my API.

In my API, I’m allowing the header like so:

header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With, X-Authorization');

I’m checking the headers using print_r(apache_request_headers())

The only reference to X-Authorization in the response is:

[access-control-request-headers] => x-authorization

I’m using CGI which I believe strips regular Authorization headers which is why I am trying a custom one.

2

Answers


  1. you will be able to see the request header under the $_SERVER super global, converted the key to uppercase, with prefix HTTP_ & replacing – to _

    for example:
    X-foo-bar: baz

    will be under:

    $_SERVER['HTTP_X_FOO_BAR']
    

    The following request:

    curl -i 0:9000/test.php -H 'X-foo-bar: baz'
    

    will return:

    HTTP/1.1 200 OK
    Host: 0:9000
    Date: Wed, 27 Jan 2021 21:33:33 GMT
    Connection: close
    X-Powered-By: PHP/7.3.24
    Content-type: text/html; charset=UTF-8
    
    baz
    

    PHP (test.php):

    <?php
    echo ($_SERVER['HTTP_X_FOO_BAR']);
    
    Login or Signup to reply.
  2. The following is working for me on Google Chrome:
    HTML file data:

    <!DOCTYPE html>
    <html>
    <head><title>test</title>
    <script>
      const test = () => {
      fetch('/3.php', {
        method: 'POST',
        redirect: 'follow',
        headers: new Headers({
          'Content-Type': 'application/json',
          'Foo': 'bar',
          'X-My-Custom-Header': 'foo-bar-baz',
          'X-Authorization': 'Basic dGVzdDp0ZXN0VG9rZW4='
        }),
        body: 'test123'
        })
        .then(response => response.json())
        .then(data => {
          console.log(data);
          document.querySelector('#response').innerHTML = data['HTTP_X_AUTHORIZATION'];
        });
      };
    </script>
    </head>
    <body>
    <button onclick="test();">Test</button>
    <pre id="response"></pre>
    </body></html>
    

    Content of 3.php:

    <?php
    header('Conent-Type: application/json');
    echo json_encode($_SERVER);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search