Thomas Rowlands
Thomas Rowlands

Reputation: 51

Troubleshooting missing "Authorization" request header in PHP

I'm currently working on a PHP REST API for a uni project, which uses JSON web tokens passed from mobile web applications using PhoneGap, or my desktop during development.

When sending the token to my server page "friends/read.php" using ajax, the server was picking up the Authorization header correctly with

$headers = getallheaders();
$authHeader = $headers['Authorization'];

but stopped doing so after several successful runs. After that point, the header is no longer being picked up.

My request code is as follows:

$.ajax({
    url: "http://localhost/chordstruck/api/friends/read.php",
    type: "GET",
    beforeSend: function (request) {
        request.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('jwt'));
    },
    datatype: "json",
    success: function (response) {
        console.log(response);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.log(jqXHR);
    }
});

Oddly enough, when killing the PHP script prematurely with die("test") and then removing die() again, the server will then start picking up the Authorization header for several more requests.

Read.php:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 'on');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization, X-Auth-Token');

$config = require_once '../config/core.php';
require_once '../config/jwt_helper.php';
// get database connection
include_once '../config/database.php';

// instantiate profile object
include_once '../objects/profile.php';

$headers = getallheaders();
$authHeader = $headers['Authorization'];

$token;

if ($authHeader) {

    list($jwt) = sscanf((string)$authHeader, 'Bearer %s');
    if ($jwt) {
        try {

            $key = $config['jwt_key'];
            $token = JWT::decode($jwt, $key, array('HS512'));

        } catch (Exception $e) {
            header('HTTP/1.0 401 Unauthorized');
            exit();
        }
    } else {
        header('HTTP/1.0 400 Bad Request');
        exit();
    }
} else {
    header('HTTP/1.0 400 No Header Found');
    exit();
}

echo "success";
?>

I have been encountering a CORS issue while developing this project, which I've countered with the above headers along with the following in my .htaccess file:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

Could this potentially be related? Any help/ideas would be greatly appreciated!

Upvotes: 3

Views: 1354

Answers (1)

Thomas Rowlands
Thomas Rowlands

Reputation: 51

The problem appears to have been indeed related to CORS and after trying a multitude of approaches, the following solution is now working.

Replacing my headers in read.php with:

// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
    // Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
    // you want to allow, and if so:
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day
}

// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        // may also be using PUT, PATCH, HEAD etc
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

    exit(0);
}

Credit goes to slashingweapon who used it to answer CORS with php headers

Upvotes: 2

Related Questions