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

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'
]);

Related

Laravel Sanctum - Store cookies on localhost subdomain

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}]

I need to add basic auth to my sanctum api

I'm using laravel sanctum and I add to middleware to my route:
Route::group(['middleware' => 'auth:sanctum'], function () {
Route::post('/sms-log',[SmsLogController::class, 'store'] );
});
But insomnia wants me to sign in:
insomnia_ss
when I remove middleware from API route working as expected. so how can I add basic auth?
In insomnia add a header so you don't get redirected to the login route, instead you get a "message":" Not authenticated."
Accept: application/json

CORS Laravel VueJS

I'm trying to do a get with axios from VueJS to Laravel which is my API.
I got this error :
Access to XMLHttpRequest at 'http://api.test/api/events/1/' from origin >'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control->Allow-Origin' header is present on the requested resource.
Uncaught (in promise) Error: Network Error
at createError (createError.js?2d83:16)
at XMLHttpRequest.handleError (xhr.js?b50d:87)
I've tried to create a middleware named 'cors' like here but it's not working for me or maybe I'm doing it badly ?
Strange thing ? is that's working with Postman.
Thank for the help ! :)
Servers are used to host web pages, applications, images, fonts, and
much more. When you use a web browser, you are likely attempting to
access a distinct website (hosted on a server). Websites often request
these hosted resources from different locations (servers) on the
Internet. Security policies on servers mitigate the risks associated
with requesting assets hosted on different server. Let's take a look
at an example of a security policy: same-origin.
The same-origin policy is very restrictive. Under this policy, a
document (i.e., like a web page) hosted on server A can only interact
with other documents that are also on server A. In short, the
same-origin policy enforces that documents that interact with each
other have the same origin.
Check this CORS library made for Laravel usage.
Installation is easy:
$ composer require barryvdh/laravel-cors
$ php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"
The defaults are set in config/cors.php
return [
/*
|--------------------------------------------------------------------------
| Laravel CORS
|--------------------------------------------------------------------------
|
| allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
| to accept any value.
|
*/
'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['Content-Type', 'X-Requested-With'],
'allowedMethods' => ['*'], // ex: ['GET', 'POST', 'PUT', 'DELETE']
'exposedHeaders' => [],
'maxAge' => 0,
];
allowedOrigins, allowedHeaders and allowedMethods can be set to array('*') to accept any value.
To allow CORS for all your routes, add the HandleCors middleware in the $middleware property of app/Http/Kernel.php class:
protected $middleware = [
// ...
\Barryvdh\Cors\HandleCors::class,
];
If you want to allow CORS on a specific middleware group or route, add the HandleCors middleware to your group:
protected $middlewareGroups = [
'web' => [
// ...
],
'api' => [
// ...
\Barryvdh\Cors\HandleCors::class,
],
];
https://www.codecademy.com/articles/what-is-cors
Tried sending Axios request from Vue app to Laravel backend.
I had CORS Error and I couldn't find the solution.
After following request execution in vendor files I found out that I was simply testing it wrong.
I was testing on url: http://localhost/api, but in config/cors.php there is:
'paths' => ['api/*', 'sanctum/csrf-cookie'],
So all I had to do was to change request to http://localhost/api/... and it started working.
Another solution is adding 'api' to paths array in config/cors.php if you want to use http://localhost/api
The problem you are facing is with the same origin policy. you can read about it on the Mozilla site (https://developer.mozilla.org/en-US/docs/Web/HTTP/Server-Side_Access_Control).
it is basally to proven un authorized access to web servers. you can change the way your web server reacts and i also in that link i have included.

Force response()->download() return HTTPS url

I have switched my Laravel 5.1 to HTTPS and everything seems fine, except the file download part.
The problem is response()->download() returns a HTTP link instead of HTTPS and I get a mixed content in Chrome, so the link is blocked.
And some code:
$headers = array
(
'Content-Type' => 'application/vnd.android.package-archive'
);
return response()->download(config('custom.storage') . $apk->generated_filename, $apk->filename, $headers);

Laravel HTTPS URL random chars?

I have just set up my custom API on my sub-domain, with an SSL certificate using NGINX. Everything works just fine (get requests etc.) however, whenever I try to authenticate I receive a 401 'Invalid credentials'.
When I die and dumped $request->all(); I figured out I suddenly have an extra GET param called 'q'? For https://api.domain.com/api/v1/login?email=test#test.com&password=test My credentials suddenly became:
q => email=test#test.com
password => test
I am absolutely baffled, does anybody have an idea whats going on? This happened when I activated my SSL cert.
I assume q is for query..
Also, here is my routes file:
Route::get('/', function() {
return 'Welcome to API';
});
/* API Version 1 */
Route::group(['prefix' => 'v1', 'middleware' => 'cors'], function() {
Route::post('/login', 'AuthController#authenticate');
Route::group(['middleware' => ['jwt.auth']], function() {
Route::resource('users', 'UsersController', ['only' => ['index', 'show', 'store']]);
Route::resource('rooms', 'RoomsController', ['only' => ['index', 'show']]);
Route::resource('reservations', 'ReservationsController');
Route::resource('customers', 'CustomersController');
Route::get('rooms/{id}/reservations', 'ReservationsController#getReservationsByRoom');
Route::get('users/{id}/reservations', 'ReservationsController#getReservationsByUser');
Route::get('users/{id}/customers', 'CustomersController#getCustomersByUser');
Route::get('reservations/{id}/customer', 'CustomersController#getCustomerByReservation');
Route::get('me', 'UsersController#getAuthenticatedUser');
Route::get('me/reservations', 'ReservationsController#getReservationsByAuthenticatedUser');
Route::get('me/customers', 'CustomersController#getCustomersByAuthenticatedUser');
});
});
TIA
What version of Laravel?
I have not seen this behavior (rewriting parameters); i'd be very surprised if Laravel was in fact the culprit (and a little disappointed).
If you're using Laravel 5.3 (and maybe 5.2, not sure), you can use $request->getContent() to see the entire request object as seen by Laravel. As the comment below suggests, I agree that it's not Laravel and more likely a problem with your config (especially considering it's when you enabled HTTPS).
Laravel does not handle the security layer (https), your web server does, so from Laravel's POV http === https, and it shouldn't care either way.
I've seen in several cases that Laravel Forcing HTTPS with Mod Rewrite so you might want to take a look into that, maybe it would help.
I've found the solution. It was indeed my NGINX configuration, Laravel would not do such a thing. It is best to have at less rewrites as possible. This was in my default setting of my /etc/nginx/sites-available/default:
location / {
try_files $uri $uri/ /index.php?q=$query_string;
}
Removing the q before query string solves of course my problem.
Thanks for all your insights

Resources