Laravel get request headers - php

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

What POSTMAN Version did you use?
Are you on your local machine or managed server, some hosting companies don't allow AUTHORIZATION HEADER.
.htaccess modification
RewriteEngine On
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

The answer from dschniepp is right, but I have problems with this too. You have to do two things:
Check if mod_rewrite is available and activated.
Update the .htaccess file of Laravel, located in the public folder.
In the first point you have to check if the "mod_rewrite" module is available through php_info function, in a separate php file. Then if it is available you have to activate it, that depends on the configuration of your webserver, in my Nitrous box I added these lines to my httpd.conf file:
<IfModule mod_rewrite>
RewriteEngine On
</IfModule>
Or you can activate the module in the .htaccess file too:
RewriteEngine On
Then in the same .htaccess file located in public folder in the root of the laravel app, you have to add these lines:
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
These lines worked for me. Your .htaccess file should look like this:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
And that's it, you should have the Authorization header in the Request::header() array. Just to clarify these is an issue with Apache, not with Laravel itself.

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

Can't send data with GET method but with POST

I'm building the Rest API in Php Slim. API working fine on localhost. Now I placed it on live server. The issue is when I send data in body using GET method, Postman shows error: 500 Internal Server Error.
. But it's working fine when changing GET to POST. I'm new in backend so don't understand what the issue is. The index.php file of API is located in subdirectory as example.com/api/public/index.php so I made some changes in .htaccess but it's not working.
.htaccess
# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php73” package as the default “PHP” programming language.
<IfModule mime_module>
AddHandler application/x-httpd-ea-php73 .php .php7 .phtml
</IfModule>
SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d [OR]
RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^(.*)$ /api/public/index.php [L,QSA]
# Don't listing directory
Options -Indexes
ErrorDocument 403 http://www.example.com/
# Follow symbolic links
Options +FollowSymLinks
# Default handler
DirectoryIndex index.php
# php -- END cPanel-generated handler, do not edit
Could I use POST instead of GET or there is something wrong?
The issue is when I send data in body using GET method
Take a look at the specification:
A payload within a GET request message has no defined semantics;
sending a payload body on a GET request might cause some existing
implementations to reject the request.
While it is possible to get some clients (e.g. Postman) to make an HTTP GET request with a body and it is possible to get some servers to read the body from an HTTP GET request, it does completely lock out some other clients (e.g. the browser APIs of XMLHttpRequest and fetch).
Either don't use a GET request or don't use a request body for this.

.htaccess file not rewriting URL's correctly when project is in subdirectory

I currently have a problem with rewriting my URL's using the .htaccess file when a Laravel project is in a subdirectory.
usually when not in subdirectory having /vacancies -> /index.php/vacancies using this below .htcaccess file works.
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine on
RewriteLog "/var/log/httpd/rewrite.log"
RewriteLogLevel 3
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^index.php [L]
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
Though now the project exists within a subdirectory I require the URL to be re written as so /vacancies -> /abc/index.php/vacancies.
The home page works correctly though any links just return a not found error.
What changes would I need to have the .htaccess file do this for me.
so on investigating further upon entering 'index.php' into the url itself the page loads correctly if this helps anymore with answering the question.
Thanks!
I wouldn't modify the default .htaccess provided in a Laravel app. You need to use Apache's directory alias in the virtual host config file for your site. You need to have the following format:
#Change the paths accordingly
Alias /vacancies /path/to/app/public
<Directory /path/to/app/public>
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride All
Order allow,deny
Allow from all
Require all granted #If using Apache 2.4 add this.
</Directory>
I managed to fix this thank you for your suggestions, This turned out to be a problem with the virtual host file and where the project was created as I have soft links let up to direct apache.
As such Apache was looking in the actual project location set in the virtual hosts file rather than the soft link one intended causing the not found issues.
Check of .ht* permissions in the apache httpd config file if you are using apache. I had the same problem and I had permissions denied problem for .htaccess file. If you are on shared host, try to contact hosting support.
Tried putting it on top of the htaccess file ? Helps for me in some kind of cases, seems weird but it does.
I notice fro your answer you've managed to "fix" this. However, you have some fundamental errors in the .htaccess file you posted, so I'm not sure how this is working exactly?
RewriteLog "/var/log/httpd/rewrite.log"
RewriteLogLevel 3
These two directives are not valid in .htaccess files and consequently will result in a 500 Internal Server Error. These can only be used directly in the server config or virtual host context. These are also Apache 2.2 directives, so won't work on Apache 2.4.
RewriteRule ^index.php [L]
(Part of the "front-controller"). You are missing a space between the first and second arguments, so this will fail to rewrite any requests to index.php - your "front-controller". (Maybe this is just a typo, but it's difficult to see a typo like this could creep in?) For example, this should be more like:
RewriteRule ^ index.php [L]
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
These directives should be before the front-controller, not at the end of the file. Otherwise, they are not going to execute for any request that is routed through your framework.
when not in subdirectory having /vacancies -> /index.php/vacancies using this below .htcaccess file works
That's not actually what the above .htaccess code does. It should simply be rewriting the request to /index.php. (The frawework/Laravel then looks at the full URL that was requested.) If it rewrote the URL to /index.php/vacancies (that some frameworks do) then you would need to read the URL using pathname information (PATH_INFO).
Though now the project exists within a subdirectory I require the URL to be re written as so /vacancies -> /abc/index.php/vacancies.
See above regarding the PATH_INFO. But if the .htaccess file is located in the document root of the site and the /abc subdirectory should be entirely hidden then you still have some work to do. You'll need to set the appropriate RewriteBase and modify the condition that removes the trailing slash off non-directories.
Otherwise, if the /abc directory is part of the URL then the .htaccess file can be moved to the /abc subdirectory, but you'll still need to modify the directives that remove the trailing slash.

Laravel 5 - Internal Pages giving Not Found Error

Actually I am deploying my laravel 5 Application on Linode Server.
My client create space for me in such type of path.
var/www/html/abcproject
I point out my godaddy domain to abcproject directory.
Now I have uploaded my all Laravel 5 files on abcproject directory.
My issue is that , my home page is working fine but my internal pages
are giving Not Fount Error.
Suppose when I try to logged in it is giving below error.
Not Found
The requested URL /abcproject/login was not found on this server.
Secondly Laravel 5 URL is getting url like that.
Supposed URL.
http://15.30.19.61/abcproject/index.php/registers
I did not understand where is and what is the issue.
One thing is my project is working fine when I try such type of URL.
http://example.com/index.php/ But In this case my URL Rewriting did not work but project is working like I can logged in, go in different pages, Logout etc.
My HTACCESS FILE
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>
Thanks
If you are powering your laravel project from a sub folder such as you mentioned above:
http://15.30.19.61/abcproject
You should add this to your .htaccess file under RewriteEngine On.
RewriteBase /abcproject
I also faced a similar issue with LAMP configuration and I resolved by enabling rewrite rules of apache. If some needs details then it can be referred at the below blog notes
http://ankgne.com/post/setting-up-digital-ocean-for-laravel-application
Step 1: Enabling mod re-write using sudo a2enmod rewrite
Step 2: Allowing the laravel .htaccess (in public directory of laravel page)
file to apply rewrite rules
sudo vi /etc/apache2/sites-available/000-default.conf and adding below lines
Note: Change "/var/www/html" to "path of laravel public folder"
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Require all granted
. . .
Step 3: Restarting web server using sudo systemctl restart apache2

Header not allowed on the server?

I have a simple API in Laravel. The routes file is like so:
<?php
Route::resource('airports', 'AirportController');
Route::resource('flights', 'FlightController');
Route::resource('reservations', 'ReservationController');
Route::get('auth', 'AuthController#index');
Route::post('auth', 'AuthController#store');
Route::delete('auth', 'AuthController#destroy');
The filter's file has a custom filter added like so:
Route::filter('auth_token', function()
{
$auth_token = Request::header('Authorization');
if(!AuthToken::where('auth_token', '=', $auth_token)->first()){
return Response::json([], 401);
}
});
All the resources need to pass before the auth_token filter. Now this works great on my local machine but as soon as I try it on my server, everything is unauthorized, even if I pass a valid token. The problem I figured by dd($auth_token) in my custom filter is that it is returning null which means that my server is not accepting the header for some reason.
My .htaccess file looks like so:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "*"
</IfModule>
I am using Postman REST client to test my application. There is only one user in the system with email 'admin#admin.com' and password 'admin12345'. You can POST these details to the /auth route and get an access token granted which can then be used to fetch other resources in the system.
The application is hosted here. What am I doing wrong?
The order of the routes might be an issue. try inverting like this and see if it works ...
Route::get('auth', 'AuthController#index');
Route::post('auth', 'AuthController#store');
Route::delete('auth', 'AuthController#destroy');
Route::resource('airports', 'AirportController');
Route::resource('flights', 'FlightController');
Route::resource('reservations', 'ReservationController');

access a folder in 'public' directory of laravel

How can I access a folder placed in the public directory of my default laravel installation. This question is for both - testing as well as live purpose.
While Testing-
I am testing on windows using XAMPP's apache http server. I have placed my app's root folder in the htdocs folder of XAMPP. Thus, when I try to access a folder in public directory, 'localhost/myappname/public/blog' it redirects me to 'localhost/blog'.
I don't want this behavior. I want it to pick up the 'index.php' file present at 'localhost/myappname/public/blog/' location. But it doesn't do so.
While Live-
I have my site live on ubuntu with apache http server. When I try to access 'mysitename.com/blog' in the firefox, it gives me this error -
Firefox has detected that the server is redirecting the request for this
address in a way that will never complete.
I have no hint about what's wrong. I have tried spending two days working with laravel's default .htaccess file(in public folder) and apache httpd.conf but still not able to resolve it. Have searched a lot over stackoverflow and google but still no clue about where I am wrong. Please guide me.
Added:
The content of .htaccess file is -
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
You just need to comment this line in your .htaccess file.
RewriteRule ^(.*)/$ /$1 [L,R=301]
Comment it or strip out from the file. This will solve both your directory /blog issue as well as redirect loop issue.
I used the Alias feature of apache to overcome this problem. I added an alias for '/blog' in my virtual host configuration.

Categories