Laravel get request headers

Viewed 56575

I am using POSTMAN to send a GET request into the api with a header containing Authorization.

I know the data header works because if it doesn't the route returns a 401 error.

I wanted to get the Authorization header like so:

$access_token = Request::header('Authorization');

But noticed that it returns NULL.

So I tried to catch the values with:

die(var_dump(Request::header()));

And noticed that it doesn't contain any Authorization header. Just host to cookie headers.


update

Should get Authorization: Bearer ACCESS TOKEN

5 Answers

In Laravel 5.5 you can read herders by using apache_request_headers simply read it in your controller by the following lines

$headers = apache_request_headers();
dd($headers['Authorization']);

Make sure you have added use Illuminate\Http\Request; in your controller

Missing authorization headers with Apache virtual host.

Apart of the solution above the culprit may be because Apache server does not allow authorization header to pass through virtual host.

To solve this issue you have to add the line allowing Apache to pass authorization header to PHP in you virtual hosts configuration. E.g. for Ubuntu 18.04 the virtual host is defined in /etc/apache2/sites-available/your-site-name.conf, see this tutorial for better context.

<VirtualHost>
    # ...
    SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
    # ...
</VirtualHost>

After updating the virtual host config do not forget to restart Apache (again e.g. Ubuntu 18.04 sudo systemctl restart apache2).

This should fix the issue.

Here is the original answer.

Posting this here as it solved my problem. This applies for sub domains but can obviously be adjusted for plain domains as well. Applied this within my routes file at the top.

$newUrl = '';
try{
    $urlParts = parse_url($_SERVER['HTTP_REFERER']) ?? '';
    $newUrl = $urlParts['scheme'] . "://" . $urlParts['host'];
    if(!stristr($newUrl, '.yourdomain.com')){
        $newUrl = 'false';
    }
}catch(Exception $e)
{}
header('Access-Control-Allow-Origin: ' . $newUrl);
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: access-control-allow-origin,cache-control,content-type,postman-token');
Related