Laravel Sanctum - Store cookies on localhost subdomain - laravel

I'm working on an webapp (Laravel/Vue) with a subdomain per organisation (companyone.mydomain.com, companytwo.mydomain.com, ...)
As authentication system I'm using Laravel Sanctum with cookies. While setting a cookie is working on localhost it's not working when using subdomains locally.
My backend is running on localhost:8000 while the frontend is running on localhost:8080. For cors reasons I've added a proxy property in vue.config.js
module.exports = {
devServer: {
disableHostCheck: true,
proxy: 'http://localhost:8000',
},
};
I've changed the /etc/hosts file so I can simulate subdomains locally
127.0.0.1 localhost
127.0.0.1 mydomain.com
127.0.0.1 companyone.mydomain.com
127.0.0.1 companytwo.mydomain.com
On the backend I've added the following lines to the .env file (and restarted the php artisan serve script)
SESSION_DOMAIN=.mydomain.com
SANCTUM_STATEFUL_DOMAINS=mydomain.com
In the Authcontroller I'm returning the cookie like this
$token = $user->createToken(Str::random(10))->plainTextToken;
$cookie = cookie('mydomain_api', $token, 60 * 24);
return response([
'token' => $token,
'user' => new AuthResource($user)
], 200)->withCookie($cookie);
The cookie settings are the following
$domain = null
$secure = true
$httpOnly = true
$sameSite = 'None'
When calling the login function I'm receiving the cookie in my browser like this
but Application -> Cookies stays empty
The request header
When sending another request to the api, no cookies are added.
How can I get the cookie in the Cookies storage?
[EDIT 1] When hardcoding the domain on the backend to mydomain.com I'm getting the following error in the browser

Update your .env
SANCTUM_STATEFUL_DOMAINS=localhost:8080,mydomain.com:8080,companyone.mydomain.com:8080,companytwo.mydomain.com:8080,::1,localhost:8080,localhost:3000

try to add folowing lines in your in .htaccess file
# Handle Authorization Header
# RewriteCond %{HTTP:Authorization} .
# RewriteRule .* - [E=Authorization:%{HTTP:Authorization}]

Related

laravel urls missing "en" from links generated from named routes

My test site is http site
my live site is https site.
My test site urls are working fine with
$url = route('admin.taskmanager.taskmanager.edit', [$task->id]);
which is generating
http://example.com/app/taskmanager/taskmanagers/89/edit
but the same url in live site is generating
https://example.com/app/taskmanager/taskmanagers/89/edit
PROBLEM:
Above live site url is generating 502 gateway error.
but when I add /en to the url like
https://example.com/en/app/taskmanager/taskmanagers/89/edit
it is working.
Both are nginx platform with same conf files.
Test site which is http site is automatically adding /en
but live site with https is not adding /en to my generated urls using routes are throwing 502 error.
Any help?
#matiaslauriti my router is as below
$router->group(['prefix' => '/taskmanager'], function(Router $router) {
$router->bind('taskmanager', function($id) {
return app('Modules\Taskmanager\Repositories\TaskmanagerRepository')->find($id);
});
$router->get('taskmanagers/{taskmanager}/edit', [
'as' => 'admin.taskmanager.taskmanager.edit',
'uses' => 'TaskmanagerController#edit',
'middleware' => 'can:taskmanager.taskmanagers.access'
]);

Get cookies from Laravel Http Client

I'm trying to login into a service (Jasper Server API) using the Http Client, but cant get the cookies from the response
This is what I'm doing:
$response = Http::withOptions( [ 'proxy' => '' ] )->
post('192.168.52.84/jasperserver/rest_v2/login?j_username=user&j_password=password');
$cookies=$response->cookies;
dd($cookies);
The output being:
GuzzleHttp\Cookie\CookieJar {
-cookies: []
-strictMode: false
}
When I do the same Get on the browser I get the cookies fine.
What could be the problem?
You can get cookie value by the following code also, get cookie by name and then get the value.
$cookies = $response->cookies()->getCookieByName('YOUR_COOKIE_NAME')->getValue();
I finally solved it.
It was just that when I did:
post('192.168.52.84/jasperserver...')
I didn't specify the scheme:
post('http://192.168.52.84/jasperserver...')
With that, I got the cookies just right.

Getting 403 Forbidden on VueJS PUT requests

Why am I getting a 403 forbidden error only on put request API from CentOS 7 vps server (while get/post are working well)?
The same piece works fine on a shared hosting server and from localhost.
I am using "Nginx + Varnish + Apache"
Whenever I try to execute any PUT request, this is the response:
Forbidden
You don't have permission to access /api/path/to/my/api on this server.
You have to explicitly permit PUT requests to your endpoint unlike GET and POST. You should look into your .htaccess settings.
This question addresses the same concern and this also.
You will have to use POST method along with _method= PUT as a form data:
let editUrl ="";
if (this.id) {
this.data._method = 'PUT';
this.data.id = this.id;
editUrl = editUrl + "/" + this.id;
}
axios.post(editUrl, this.data)
.then(resp => {
})
.catch(() => {
});
}
Config your apache virtual host by these conditions:
<Limit GET POST PUT OPTIONS>
Require all granted
</Limit>
<LimitExcept GET POST PUT OPTIONS>
Require all denied
</LimitExcept>
Maybe your problem solved.

request() not secure in Laravel with load balancer and TrustedProxies

Why is request()->isSecure() returning false when visiting a HTTPS-url? I am using Laravel Forge and I have a load balancer. Logging the request I get this data:
request()->url(), // "http://xx.xx"
request()->isSecure(), // false
request()->getClientIps(), // XX.XX.XX.XX
In TrustProxies (which is added in the $middleware array in Http/Kernel.php):
protected $proxies = [
'XX.XX.XX.XX', // exactly the same as in the logged data above
];
In my AppServiceProvider's boot() method:
if (env('APP_ENV') == 'production') {
\URL::forceScheme('https');
}
Edit:
I am also using Cloudflare, and I have added all the Cloudflare proxies to $proxies as well. Check the logs, I see these headers in the request:
X-Forwarded-Proto: http
Cf-Visitor: {"scheme":"https"}
Referer: https://xx.xx/someurl
While You are using Cloudflare You should to use "Full SSL/TLS encryption mode".

Get authorization from Lumen and header from Laravel

In project, all API calls are from Lumen. Front is developed in Laravel. We are calling Lumen APIs using Guzzle http client guzzleHttp.
Now, I need to set header Authorization for all API calls so I'm sending token in header from Laravel but in Lumen I can't get token in Lumen request header.
Below is the example code.
Laravel controller code:
public function get_category(){
$accessToken = 'kjdhfdkjfhdkjfhfjkdf9875443213456';
$response = \Guzzle::request("GET","example.com", "categories",['headers' => [
'Authorization' => $accessToken
]]);
$category_all = json_decode($response->getBody()->getContents(),true);
return $category_all;
}
Lumen middleware code:
public function handle($request, Closure $next)
{
dd($request);
}
In Lumen request I can't get token in request header.
If you're using Apache, by default it remove the Authorization header.
You've to add this settings in the .htaccess project's file or in the apache .conf file (usually in /etc/apache2/sites-available/):
RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
Header set Access-Control-Allow-Headers "Authorization"

Resources