I'm doing a laravel app but when I try to create an account it gives a csrf error..
When I check what cookies the website have, I find that I have no cookies, there should be a XSFR-TOKEN and a laravel_session cookies, but laravel is not generating any of those cookies, so it gives me a token not found when i try to create an account.. anyone know why it does that? any idea how to fix that?
Also just installed a new clean laravel and find out if I put the "app" view inside of a folder it also happends and doesnt generate the cookies, I have tried to change the folder permissions but the problem persists.
Open your http app/Http/Kernel.php file and check if your Kernel::$middleware array contains:
Illuminate\Cookie\Middleware\EncryptCookies
Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse
Illuminate\Session\Middleware\StartSession (this is middleware which is responsible for passing data to session driver in Laravel 5)
Illuminate\View\Middleware\ShareErrorsFromSession
App\Http\Middleware\VerifyCsrfToken
To clarify - Kernel::$middleware array contains middleware which is executed on every HTTP request. By default it contains middleware that is essential for session support in Laravel. Perhaphs you accidentaly deleted them.
Here is original file: https://github.com/laravel/laravel/blob/v5.0.22/app/Http/Kernel.php
Related
I am using spatie library to upload some files which will be saved to the storage folder. What I want to accomplished at the moment, is to view those files or images when I am an authenticated user. I've tried creating a symlink using this command ,
php artisan storage:link
But this makes those file to be seen publicly. What I only want is to view those file, only when the user is an authenticated user. So far this is what I did but it seems like I miss something.
ROUTE :
Route::get('/storage/{filePath}', 'ComplaintsController#fileStorageServe')->where(['filePath' => '.*'])->name('complaints.viewfile');
CONTROLLER :
public function fileStorageServe($file) {
// know you can have a mapping so you dont keep the sme names as in local (you can not precsise the same structor as the storage, you can do anything)
// any permission handling or anything else
// we check for the existing of the file
if (!Storage::disk('local')->exists($filePath)){ // note that disk()->exists() expect a relative path, from your disk root path. so in our example we pass directly the path (/.../laravelProject/storage/app) is the default one (referenced with the helper storage_path('app')
abort('404'); // we redirect to 404 page if it doesn't exist
}
//file exist let serve it
// if there is parameters [you can change the files, depending on them. ex serving different content to different regions, or to mobile and desktop ...etc] // repetitive things can be handled through helpers [make helpers]
return response()->file(storage_path('app'.DIRECTORY_SEPARATOR.($filePath))); // the response()->file() will add the necessary headers in our place (no headers are needed to be provided for images (it's done automatically) expected hearder is of form => ['Content-Type' => 'image/png'];
// big note here don't use Storage::url() // it's not working correctly.
}
VIEW :
#foreach($complaint->attachments as $attachment)
{{ $attachment->file_name }}
#endforeach
When I click the link it will give me something like this.
http://127.0.0.1:8000/complaints.viewfile/http%3A%2F%2F127.0.0.1%3A8000%2Fstorage%2F3%2F60580fdeadc55_worship.jpg
Please help. Thank you...
You need to understand how files are served by a web server and how that interacts with a laravel application.
You likely have nginx or apache set up to serve files from the public folder of your laravel app. ie: /var/www/sites/laravel-site/public.
When an HTTP request is sent to your server, if your nginx or apache is configured to serve files like laravel-site.com/storage/documents/secrets.pdf statically, then your laravel application code will never even be run, and you cannot control access to these files at the application level.
If you want to setup access control to files, you will need to first ensure the requests are not going to be served statically, and second setup a route to serve the files after checking if the user/request has permission to access the file(s) you want to serve.
There are lots of other great answers and resources on how to do this.
Correct me if im wrong but isn't the easiest way to do that via system-settings ? Like you have different Users and you just put them in different groups that have different rights for folders/files.
I have to download some files from my webapp with laravel 5.6 and I am using the local storage.
I have my routes like downloads/{file} with the auth middleware and it's working properly.
The storage url is the default from laravel www.myweb.com/storage/files/ ...
the thing is if I use the route www.myweb.com/downloads/foo.pdf the controller is working properly and i must be logged in to download the file
but if I access from www.myweb.com/storage/files/foo.pdf I can see the file without being logged in
How can i solve this? should i create another controller or route to handle this?
should i create a route like
Route::get('/storage/files/{file}', 'FilesController#download')->middleware('auth');
/storage/files is already actual path of the storage. to avoid conflict change your route to other path
Route::get('/storage/files/{file}', 'FilesController#download')->middleware('auth');
change to (sample)
Route::get('/files/{file}/download', 'FilesController#download')->middleware('auth');
then do your logic in FilesController
When logging in, authentication works and the user is redirected to the logged-in page (/home at first but I also tried changing to /dashboard) but then the session seems to become lost as it shows an empty array when logging on the logged-in controller.
My setup involves using Redis as a session store but I have tried file and database drives as well with the same results.
Even stranger, I am able to view the session data in my redis cli without any issues.
Some "fixes" I have tried to no avail are:
- removing underscores from session cookie name (as well as dashes/hyphens)
- changing session domain setting to all combinations of main domain and subdomain
Does anyone have any ideas on any other possible fixes?
UPDATE:
Other fixes tried:
alternative session drivers (file, database, and cookie)
php artisan cache:clear
php artisan clear-compiled
Where did you write your Routes ?
Please note that the web middleware uses the default Laravel Session.
So routes written in routes/web.php are the ones using Laravel Session. You can also try using the file driver, but make sure the /storage folder has at 0755 permission.
also, can you please check you App\Providers\RouteServiceProviders mapWebRoutes() method looks like this?
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* #return void
*/
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
Assuming you didn't modify the app\Http\Kernel.php
The problem resolved with me after remove \App\Http\Middleware\EncryptCookies::class from web inside $middlewareGroups in app\Http\Kernel.php file.
I am using laravel 4.2. After my login code, I redirect to another route for dashboard. But session is not persistent on my dashboard function
This is my code on login function
Session::put('email', $userObject->email);
Session::put('firstName', $userObject->first_name);
Session::put('lastName', $userObject->last_name);
Session::save();
return Redirect::to('/account/dashboard');
if i try to print Session::all() right after Session::save(); I could get the values, But after redirection got nothing. Of course my storage path has the write permissions (0777) Session driver is 'file' Also tried with database, but no luck Any help is highly appreciated, stuck on this for a week almost.
Issue caused because of PHP closing tag on a payment gateway library. It was included in the autoload.
Things to check if session issue comes:
Check for errors using debug true.
Check for exceptions in log file(storage folder)
Do not include PHP closing tag on your files. Before installing a custom library make sure that it doesnot have a closing tag or an error
Do not copy code from websites. if you do so, just paste it to notepad and then copy paste to your editor
I'm hosting my PHP Yii application on AWS Elastic Beanstalk and hence using the database to store sessions. I've successfully implemented facebook login using Hybridauth on a shared hosting environment. When I host on Elastic Beanstalk facebook login gives the error:
"You cannot access this page directly"
The URL ends up as:
http://mydomain.com/hybridauth/default/callback?hauth.start=Facebook&hauth.time=1393106016
I've learnt from here that this is related to facebook calling back to the application but finding a different session. Endpoint.php then throws the error:
# Init Hybrid_Auth
try {
// Check if Hybrid_Auth session already exist
if ( ! isset( $_SESSION["HA::CONFIG"] ) ) {
header( "HTTP/1.0 404 Not Found" );
die( "You cannot access this page directly." );
}
How can I ensure facebook calls back to the same session and successfully signs in with hybridauth?
Its due to PHP SESSION name
If you have change session name in confing file of Yii. Then you have to use add this session_name('samar_v4'); in file protected/modules/user/vendors/hybridauth/Hybrid/Endpoint.php in starting of functoin authInit
Check your Facebook application's redirect URL. Facebook doesn't allow multiple redirect URLs. So each time you change your hosting/domain/address, you'll have to reconfigure the Facebook application's redirect URL or use a different set of credential.
Also your redirect URL should be something like this: http://mydomain.com/hybridauth/?hauth.done=Facebook
This worked for me as well:
"base_url" => "https://example.com/inc/hybridauth/",
I changed it to
"base_url" => "https://".$_SERVER['HTTP_HOST']."/inc/hybridauth/",
For me it worked on the main domain but not on a subdomain. I worked out it was the base_url in config.php that caused the error.
Instead of
"base_url" => "https://mydomain.com/inc/hybridauth/",
I changed it to
"base_url" => "https://".$_SERVER['HTTP_HOST']."/inc/hybridauth/",
Now it works anywhere I put it.
For anyone else struggling with this issue, and its not related to the www-domain registration issue, my problem had to do with not being able to write to the php session directory. Not sure how or when it was altered, but if you cannot write to /var/lib/php/5.5/session, hybridauth will not work.
As per the other answers, I believe this is a session problem, perhaps the session is started under the wrong domain and then cannot be re-fetched under the other domain.
I solved this by removing various ServerAlias settings from my development Apache config.
this 'caused' the error:
ServerName mydomain.com.au.localhost
ServerAlias www.mydomain.com.au.localhost
ServerAlias localhost.mydomain.com.au # << using this one
this fixed the error:
#ServerName mydomain.com.au.localhost
#ServerAlias www.mydomain.com.au.localhost
ServerName localhost.mydomain.com.au # << using this one
apachectl restart
(I normally use mydomain.com.au.localhost so I'm leaving them in for later use.)
I had the same issue using Hybrid Auth 2.8. It relates to our custom session handler which is set by session_set_save_handler().
Hybrid Auth uses standard PHP sessions, so after redirecting and opening a new session, Hybrid Auth starts using standard PHP file sessions instead of your custom session handler. This result in the loss of config data from our session and getting this error message.
I resolved this issue by adding our own custom session handler at the top of hybridauth/index.php (located in the same dir as config.php and live.php).
This forces Hybrid Auth to use your custom session handler.
I found this problem that seems unsolvable. I was giving up, that's when my instinct led me to do a test and voila everything working.
For anyone with the same problem have a question: The file that calls the API is in the same directory it?
Me only worked when I put my file in the same folder as the config.php file. Try it there and tell me if it works!
A hug
and Greetings to all!
I solved my particular HybridAuth "You cannot access this page directly" error with the domain name on the session cookie. My app exists on a subdomain and I'd designed the redirect to point to socialize.sub.domain.tld, and the cookie wasn't reaching the _Endpoint.
Changing the session domain to .domain.tld solved it. - Hope this helps :)