laravel 6 session restart through each request - laravel

I'm working with Laravel 6, and my session driver is file. I've faced a 419|page expired when I submit a form with post action and after tracing the codes I found out the session will restart after submission. Everything is good on local but on the server I've got this issue.
I tried with a raw Laravel project and it worked!
I've already checked directory permission, config/session.php,.env file.
.env
SESSION_DRIVER=file
SESSION_LIFETIME=120
config/session.php
'driver' => env('SESSION_DRIVER', 'file'),
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => false
Tnx for responding.
the problem is not because of CSRF token, it's session's fault. evry time a new session and new token will be started so the token thet I send from input will be checked with another token !!!

If your form is in a blade, after starting the <form>, add a csrf field by putting #csrf.
If you're sending the POST request from somewhere else (i.e. from some other domain/subdomain that is not project domain) you may want to disable CSRF check by adding it in VerifyCsrfToken.php (\app\Http\Middleware\VerifyCsrfToken.php) like this:
class VerifyCsrfToken extends BaseVerifier
{
protected $except = [
// Place your URIs here
];
}

Related

Laravel 9 419 Unknown Status on sending POST request

Good day, I'm having trouble on sending post data to my Laravel project, It always shows Page Expired (419) on this,
Error 419 on POST
Here's the things I have done before coming up to my question:
Added SESSION_SECURE_COOKIE=FALSE on .env
Changed the config/session.php from 'secure' => env('SESSION_SECURE_COOKIE'), to 'secure' => env('SESSION_SECURE_COOKIE', false),
Added ob_start(); at the beginning of public/index.php like this <?php ob_start(); use Illuminate\Contracts\Http\Kernel; use Illuminate\Http\Request;
This is my route
Route::post('/data', [AdminController::class, 'getSensorData']);
Also in I'm sending the data to the database from the post request using the controller.
The request works fine when the method is GET.
200ok on GET
Edit: It's working now, the fix was from #Ahmed Hassan. Thank you.
this issue occur because you didn't send the CSRF token with the request
just add #csrf inside your form and it will work
also, you can exclude your URL in the $except list in the App\Http\Middleware\VerifyCsrfToken
I hope it's helpful

Laravel Sanctum unauthenticated using postman

I follow the Laravel official document step by step.
When I send a request to {{host}}/api/login, I can receive the response that includes the token. Everything is correct.
But when I try to send a request to {{host}}/api/user, it is always unauthenticated.
I checked my code several times, I cannot fix it.
In my .env file, I set as following, my backend host is http://laravel_8_api.test
SESSION_DOMAIN=.laravel_8_api.test
SANCTUM_STATEFUL_DOMAINS=.laravel_8_api.test
How can I make it work? Please help me.
The code is in this link https://github.com/ramseyjiang/laravel_8_api
Try this if you haven't
The reason this isn't working is that Sanctum is denying the authenticated request based on the referrer.
Add Referer to the request header in postman.
//api.php
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
middleware should be auth:sanctum instead of auth:api
In the official document, it forgets to modify the config/auth.php
'api' => [
'driver' => 'sanctum',
'provider' => 'users',
'hash' => false,
],
After that, it will fix this issue.
Don't need to modify code in the code in the api.php
I mean it doesn't need to change auth:sanctum to the auth:api, if change it, it will make another issue as the link Laravel Sanctum : column not found: 1054 Unknown column 'api_token' in 'where clause'
Try this solution, may it will help you.(It helped me)
first you check is that your bearer token which you sending in header is really reaching to your app server?
Lets check it:
put this code in your route/api.php file
print_r($_REQUEST);
print_r($_SERVER);
exit;
now lets send postman request,
in response you will get a line like this
"[REDIRECT_HTTP_AUTHORIZATION] => Bearer 6|4rxthBID7kiSleFglD30aphZu3poiDYJjWMJgZZc"
if this line is missing then its mean your .htaccess file is not allowing to pass token to server.
So the solution is very easy, just add this line to your .htaccess file
#Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

Laravel automatically logged out with multiple users?

I'm currently developing a website with multiple users.
I tested logging in the other users in incognito and after a few seconds some of them automatically logs out.
When using only 1 user the website doesn't logs out and working fine.
I'm using
I already changed the SESSION_DRIVER in to database in the .env file but still logging out occurs. Do you know any explanation about this? Thank you.
public function grant_auth($name,$section)
{
$data_auth =
[
'name' => $name,
];
if(Auth::attempt($data_auth))
{
Session::put('section',$section);
Session::save();
return Redirect::route('dashboard');
}
else
return Redirect::to('login');
}
Im granting authentication using this code. I didn't use php artisan make:auth.
change your config/session.php
'lifetime' => 4320,
'expire_on_close' => false,
after that clear config cache
php artisan config:cache
more here: Laravel session expire time for each session

Laravel keeps logging me out after login

I have Laravel set up. I am running multiple domains to it. Before yesterday I had one top level domain and a few sub domains. I added another TLD yesterday and everything started working weird. Specifically, when trying to log into the admin section it redirects to the home page. I have one admin but server domains coming to the site. My route group it:
Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function() {
Sometimes is actually brings me into the admin but as soon as I click on a link I get logged out and redirected to the home page. I keep seeing 401 errors in the console as well.
What would cause this?
edit
Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function() {
Route::get('/', 'AdminController#index');
Route::get('/pages', 'AdminController#pages');
Route::get('page/create', 'AdminController#createPagePage');
Route::post('createPage', 'AdminController#createPage');
Route::get('/page/edit/{page_id}', 'AdminController#editPagePage');
Route::post('editPage', 'AdminController#editPage');
});
$redirectTo = '/';
If you are using Linux, try to check the session file permissions and change them so the app can write session keys on that file and if it doesn't work, try to change the session driver to database.
how to change the session driver?
Go to your .env file and change SESSION_DRIVER=file to SESSION_DRIVER=database.
create a session migration: php artisan session:table.
composer dump-autoload.
Finally migrate (php artisan migrate).
Have you setting the SESSION_DOMAIN right?
One thing you may notice is that session isn’t saved when the user is logged-in in one store and goes to another. To fix that issue, we’ll need to add a SESSION_DOMAIN variable to our .env file, for example:
SESSION_DOMAIN=’.example.com’
That’s all, now user session will be shared across all shops/subdomains in our app.
https://medium.com/#maxkostinevich/how-to-build-multi-domain-laravel-application-e6d87d5e507b
If you are confident with the domain setup correctly. Please verify these few things.
1. Your config/session.php is correctly setup to support multiple domains.
'driver' => env('SESSION_DRIVER', 'file'), // check /storage folder writtable recursivelly.
'domain' => env('SESSION_DOMAIN', null), // verify if single domain is not given in .env or in settings.
'same_site' => null // it should not be strict if you have ajax request across these domain. I mean from javascript you may try to request to other domain.
etc...
2. Confirm, if your routes are not group under domain specific. something like:
Route::group(['domain' => 'xxx'], function($params)
{
// your routes..
});
3. If there is any hardcoded domain verification/conditions or redirection added in code.
4. Any values in .env poiting to single domain.
5. Also don't forgot to clear the cache/compiled view/routes and delete the temp files once. like generated files inside /app/bootstrap & /storage
// Clear Application Cache
php artisan cache:clear
// Clear route cache
php artisan route:cache
// Clear config cache
php artisan config:cache
// Clear compiled view files
php artisan view:clear
6. Any thirdparty package might contains the domain settings. Make sure to verify the files in your /config folder.
7. Check the url rewrite settings in .htaccess
8. Do confirm if there is any proxy settings are there or any software installed on server - very rare case.
In case still having issue, please restart the apache/nginx service once because sometimes the config changes not effected after change that might need server restart.
Hopefully it helps.

Persisting sessions across subdomains in Laravel 5

Using 5.0
in config/session.php I have set 'domain' => '.example.com' but it is not working. I cannot persist a session on even one domain like this.
My site has many subdomains:
vancouver.example.com
newyork.example.com
etc... they are hosted on the same server and are the same Laravel app (share the same storage directory)
I login with the correct credentials, upon which the app redirects to another page on the site, and I have no session at that point. var_dump(Auth::user()) shows null even though I logged in with the correct credentials.
storage/framework/sessions shows 14 different files there, they are all for me and I cleared them out before I started testing this.
I'll attach my AuthController#postLogin method below, which works fine if session.php 'domain' => null
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if ($this->auth->attempt($credentials, $request->has('remember'))) {
Session::flash('message', 'You are now logged in.');
Session::flash('status', 'success');
if (str_contains($_SERVER['HTTP_REFERER'], '?goto=')) {
$params = explode('?', $_SERVER['HTTP_REFERER'])[1];
$target = explode('=', $params)[1];
} else {
$target = '/';
}
return redirect($target);
}
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => $this->getFailedLoginMessage(),
]);
}
Figured it out. Update domain => '.example.com' in session.php and clear the cookies for the site in question.
#gadss
you need to add session table like this
php artisan session:table
composer dump-autoload
php artisan migrate
and change .env to
SESSION_DRIVER=database
also modify config/session.php
'driver' => env('SESSION_DRIVER', 'database') and
'domain' => '.yourdomain.com'
after that clear your browser's cache and cookies.
You'll need to update the session configuration to persist the session in domain-wide including subdomains. Follow the steps given below.
Go to config/session.php and update the domain with prefix . as config => '.your-domain.com'.
Then clear your application cache, Open the Chrome DevTool and Go to Application > Application > Clear Storage. You'll need to clear out the previous cookies also.
run artisan command php artisan config:cache or php artisan config:clear to drop previously cached laravel application configs.
If you are using database as the session driver, You need to create a session table for that. run command php artisan session:table to generate the session table migration and then migrate it using php artisan migrate. Then perform the three steps given above.
With Laravel 8 it becomes more simplier :
Add SESSION_DOMAIN to your .env file :
SESSION_DOMAIN=.yourdomain.tld
Clear configuration cache :
php artisan config:cache
Delete your browser sessions cookies, then session become shared between all your subdomains.
In my case I used to AutoLogin user to subdomain once account is created on www. domain. Worked fine.
Have you tried storing the sessions in the database, memcached, or redis instead of in files? I had a similar situation to yours and storing sessions in the database solved the issue for me.
For some reason Laravel's session driver doesn't handle cross domain sessions correctly when using the file driver.
If someone still gets the problem with subdomain cookie. Try to change Session Cookie Name in config/session.php
If someone needs to sync session in subdomains with different laravel application sharing same database
Follow all the instructions of #Kiran Maniya
Then you have to keep same application name in order to get same session name. Or just change the cookie config in config/session.php
You can hardcode it if keeping same name is not possible.
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
)
to something like:
'cookie' => env(
'SESSION_COOKIE',
'session_sharing_application_session'
)

Resources