“The page has expired due to inactivity” - Laravel 5.5 - 小众知识

“The page has expired due to inactivity” - Laravel 5.5

2013年01月27日 14:18:05 苏内容
  标签: Laravel
阅读:7328

My register page is showing the form properly with CsrfToken ({{ csrf_field() }}) present in the form).

Form HTML

<form class="form-horizontal registration-form" novalidate method="POST" action="{{ route('register') }}">
        {{ csrf_field() }}
        ....
</form>

I am using inbuilt authentication for the users. Have not changed anything except the routes and redirects.

When I submit the form (just after reloading also), it gives that The page has expired due to inactivity. Please refresh and try again. error.

My be I am missing a very small thing. But not sure what it is. Any help?

Update

Found the issue. The session driver was set to array. Changed it to file and the error is gone now. But what is wrong if I use array?


If you're coming to this answer directly from a search, make sure you have already added the csrf token to your form with {{ csrf_field() }} like the OP.


If you have your session driver set to file:

May have something to do with the storage_path not being writable. This is where it stores session data regarding tokens if you're using file based sessions. The can be verified with is_writable(config('session.files'))


For the OP, the session driver was set to array. Array is for testing only. Since data is not persisted, it will not be able to compare the token on the next request.

The array driver is used during testing and prevents the data stored in the session from being persisted.

https://laravel.com/docs/5.5/session#configuration


Check config/sessions.php

Lastly, an issue I just had, we had a project which has the session domain and secure settings in config/session.php but the development site was not using HTTPS (SSL/TLS). This caused this generic error since sessions.secure was set to true by default.

Ok. But for now it is in development. So if I use array, why it was giving me that error? – Sougata Bose Sep 10 '17 at 14:46                 @SougataBose testing is not development. Array data is not persisted... – Devon Sep 10 '17 at 14:46
That's the reason one should go through the DOCs properly.. :) – Sougata Bose Sep 10 '17 at 14:50
My problem was not solved. I did the basics truly. But I'm using custom providers and services. There is no problem when I call a controller method but when I run a service method in a controller that called with post request, the problem appears! – Behnam Azimi Dec 17 '17 at 22:26
I had a similar issue with sessions but in regards to testing. Turned out when I was using Carbon::setTestNow($time); in the tests I was not clearing it by using Carbon::setTestNow();afterwards. – riotCode Aug 1 at 23:52

I ran into the same issue in Laravel 5.5. In my case, it happened after changing a route from GET to POST. The issue was because I forgot to pass a CSRF token when I switched to POST.

You can either post a CSRF token in your form by calling:

 {{ csrf_field() }}

Or exclude your route in app/Http/Middleware/VerifyCsrfToken.php

 protected $except = [
        'your/route'
    ];
csrf_field() present in the form. The accepted answer describes the issue. Thanks. – Sougata BoseSep 18 '17 at 4:37
In my case, I was receiving a POST from a 3rd party, so adding the csrf_field() was not an option. Since CSRF was not a factor in my case, adding an exception to this route solved the problem. Thanks. – Fábio Duque Silva Oct 31 '17 at 15:44
My problem was not solved. I did the basics truly. But I'm using custom providers and services. There is no problem when I call a controller method but when I run a service method in a controller that called with post request, the problem appears! – Behnam Azimi Dec 17 '17 at 22:28
Please do not disable CSRF verification! It's very important to protection to have. Learn how to properly send the token and protect your logged in users from malicious javascript that can submit actions on their behalf. – Devon Apr 8 at 0:17

Try all of them.

composer dump-autoload
php artisan optimize
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear
++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++

This caused because of Illuminate\Session\TokenMismatchException look at this code sample how to handle it properly:

https://gist.github.com/jrmadsen67/bd0f9ad0ef1ed6bb594e

++++++++++++++++++++++++++++++++++++++++++++++++++

Some information is stored in the cookie which is related to previous versions of laravel in development. So it's conflicting with csrf generated tokens which are generated by another's versions. Just Clear the cookie and give a try.

++++++++++++++++++++++++++++++++++++++++++++++++++
  • No help.. After clearing all cookies also – Sougata Bose Sep 10 '17 at 14:34
  • did you able to see <input type="hidden" name="_token" value="Umr1AlG3sScdUWGtMoHcQPPKASsR7qsd5ZE1H3Xv"> kind of code in generated html ? – Suresh Velusamy Sep 10 '17 at 14:40
  • It is there. Found the issue. The session driver was set to array. Changed it to file and the error is gone now. – Sougata Bose Sep 10 '17 at 14:43
++++++++++++++++++++++++++++++++++++++++++++++++++

My case was solved with SESSION_DOMAIN, in my local machine had to be set to xxx.localhost. It was causing conflicts with the production SESSION_DOMAIN, xxx.com that was set directly in the session.php config file.

++++++++++++++++++++++++++++++++++++++++++++++++++

For those who still has problem and nothing helped. Pay attention on php.ini mbstring.func_overload parameter. It has to be set to 0. And mbstring.internal_encoding set to UTF-8. In my case that was a problem.

++++++++++++++++++++++++++++++++++++++++++++++++++

I change permission to storage and error was gone. It seems lack of permission was the issue.

sudo chmod -R 775 storage/
++++++++++++++++++++++++++++++++++++++++++++++++++

I had the app with multiple subdomains and session cookie was the problem between those. Clearing the cookies resolved my problem.

Also, try setting the SESSION_DOMAIN in .env file. Use the exact subdomain you are browsing.

++++++++++++++++++++++++++++++++++++++++++++++++++

In my case, the site was fine in server but not in local. Then I remember I was working on secure website.
So in file config.session.php, set the variable secure to false

'secure' => env('SESSION_SECURE_COOKIE', false),
++++++++++++++++++++++++++++++++++++++++++++++++++

Be sure to have the correct system time on your web server. In my case, the vagrant machine was in the future (Jan 26 14:08:26 UTC 2226) so of course the time in my browser's session cookie had expired some 200+ years ago.

++++++++++++++++++++++++++++++++++++++++++++++++++

set mbstring.func_overload = 2

it helped me

++++++++++++++++++++++++++++++++++++++++++++++++++

I have figured out two solution to avoid these error 1)by adding protected $except = ['/yourroute'] possible disable csrf token inspection from defined root. 2)just comment \App\Http\Middleware\VerifyCsrfToken::class line in protected middleware group in kernel

++++++++++++++++++++++++++++++++++++++++++++++++++

You Must have file type 

FileName.blade.php in laravel
FileName.erb.rb in Ruby and Rails

and append any one

  1. {{ csrf_token() }}
  2. <input type="hidden" name="_token" value="{{ csrf_token() }}" >
  3. <meta name="csrf-token" content="{{ csrf_token() }}">
++++++++++++++++++++++++++++++++++++++++++++++++++
  • This is not about Ruby and Rails, also he already has a csrf token. – Casper Spruit Oct 11 '17 at 19:27

I was facing same issue with laravel 5.4 .. and then following command works for me :)

chmod 777 storage/framework/sessions/

before this, it was chmod 775 storage/framework/sessions/ ... hence I was facing the issue...

Happy coding



From Laravel 5.3 docs

The Auth::routes method now registers a POST route for /logout instead of a GET route. This prevents other web applications from logging your users out of your application. To upgrade, you should either convert your logout requests to use the POST verb or register your own GET route for the /logout URI:

Option One: Route::get('/logout', 'Auth\LoginController@logout');

For more about upgrade please have a look at this https://laravel.com/docs/5.3/upgrade

Option 2

//Insert this on your head section
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">

<!-- Scripts -->
<script>
    window.Laravel = <?php echo json_encode([
        'csrfToken' => csrf_token(),
    ]); ?>
</script>

Where you want you logout

 <ul class="dropdown-menu" role="menu">
   <li>
       <a href="{{ url('/logout') }}" onclick="event.preventDefault();
            document.getElementById('logout-form').submit();"> Logout
         </a>

        <form id="logout-form" action="{{ url('/logout') }}" method="POST" style="display: none;">
             {{ csrf_field() }}
         </form>
   </li>
</ul>

Cheers

++++++++++++++++++++++++++++++++++++++++++++++++++
  • You state <meta name="csrf-token" content="{{ csrf_token() }}"> I am unfamiliar - is this a shorthand for <meta name="csrf-token" content="<?php csrf_token() ?>" – Datadimension Oct 17 '16 at 17:47 
  • yes that is correct – usrNotFound Oct 17 '16 at 23:29
  • The scripts part messes up my whole syntax, is there a typo somewhere? – nclsvh Dec 29 '16 at 8:46
  • @NicolasV what seems to be the issue? – usrNotFound Dec 31 '16 at 4:03
  • @usrNotFound I use Atom and the colorscheme for my syntax goes crazy when I include this, makes me think there is something not closed off properly. But it runs, does not give an error.. ! See here: nl.tinypic.com/r/290zwy1/9 – nclsvh Jan 3 '17 at 9:30
++++++++++++++++++++++++++++++++++++++++++++++++++

I solved this problem by editing the file config->session.php

'domain' => env('SESSION_DOMAIN', null),

and removing SESSION_DOMAIN from the file (.env)

and finally composer dumpautoload

++++++++++++++++++++++++++++++++++++++++++++++++++
  • There is no SESSION_DOMAIN property. Do you mean SESSION_DRIVER? – Semo Mar 3 '17 at 11:15
  • There is 'domain' => env('SESSION_DOMAIN', null), in session.php – Rasim Mar 6 '17 at 6:56

Actually i have the same issue in Laravel 5.4, when I upload a file using a form, I sent the token and the file uploads correctly. The issue appears when I upload a file that exceeds the max filesize upload. So, just add an exception in the VerifyCsrfToken.php for the route and the message disapears, but the file doesn't get upload.

use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */

    protected $except = [

        'anexoSesion',
    ];
    public function handle($request, Closure $next)
    {
        return parent::handle($request, $next);
    }

}
++++++++++++++++++++++++++++++++++++++++++++++++++

I had the same problem. I run Laravel / PHP on a Windows machine with IIS. If you do as well, please make sure, the user IUSR have modify rights on the project directories. After permitting the user, the error was gone.

++++++++++++++++++++++++++++++++++++++++++++++++++

This issue will generally occur due to permissions. As Manish noted you can chmod 777 on your sessions folder, however, I would not recommend this ever. First check if you have the same issue with the app using artisan serve (as opposed to serving your app via Nginx or Apache). If you don't then it is a permissions issue and you can change the ownership of the folder accordingly. Most likely it is the www-data user that needs permissions to write to the folder, however, you will want to check your environment to make sure as the user will differ in some cases.

++++++++++++++++++++++++++++++++++++++++++++++++++

To solve this add those two lines in the route file (e.g web.php)

Route::get('/', 'HomeController@index');// so when you logged out it go back 
Route::get('/home', 'HomeController@index');

This solved the problem for me. Hope that help.

++++++++++++++++++++++++++++++++++++++++++++++++++

Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php

use Closure; // import

protected $except = [
    //
];

public function handle($request, Closure $next)
{
    $response = $next($request);

    if (last(explode('\\',get_class($response))) != 'RedirectResponse') {
        $response->header('P3P', 'CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
    }

    return $response;
}

or


for all url

protected $except = [
    '*'
];

or


If there is no use

Illuminate\Foundation\Http\Kernel.php

// \App\Http\Middleware\VerifyCsrfToken::class

this line add comment

++++++++++++++++++++++++++++++++++++++++++++++++++

I have added SESSION_DOMAIN=localhost in my .env file when my APP_URL is APP_URL=http://localhost. It works for me I use laravel 5.3

++++++++++++++++++++++++++++++++++++++++++++++++++

Out of the box, Laravel comes with web and api middleware groups that contains common middleware you may want to apply to your web UI and API routes

If you check your app/Providers/RouteServiceProvider.php, you will find that by default, a webmiddleware group is applied to all your routes in routes/web.php.

protected function mapWebRoutes()
{
    Route::group([
        'middleware' => 'web',
        'namespace' => $this->namespace,
    ], function ($router) {
        require base_path('routes/web.php');
    });
}

Now, if you go check your app/Http/Kernel.php and take a look at the $middlewareGroupsproperty, you will find a new EncryptCookies middleware. You can read about it, but if you remove this middleware from the web middleware group, your app might not give the TokenMismatchException which you are getting currently.

++++++++++++++++++++++++++++++++++++++++++++++++++

I faced this issue because I set 'secure' => env('SESSION_SECURE_COOKIE', false), to true for my localhost. The value is in the project-folder/config/session.php file. Since my localhost wasn't https that's why I was facing the issue. After making it false for my localhost the issue disappeared.

++++++++++++++++++++++++++++++++++++++++++++++++++

I am also facing this problem when using laravel5.4 for rest API. Just add the route name to the app/Http/Middleware/VerifyCsrfToken.php file.

protected $except = [

    'test/login',
];

After adding the line, then I run the API, it executes successfully.


扩展阅读