Laravel 5.2 CSRF Token expires too quickly

2019-07-30 08:28发布

问题:

I am working on Laravel 5.2 application and I am facing this issue for all my views.

The CSRF token is getting expired too quickly. In fact, I am just occupying the time to fill up the form and as soon as I submit it,I get TokenMismatchException exception.

I tried to search for the problem on Google, found git for some similar issues and even tried on Laracast for similar problem without any success.

My .env file has some lines like this:

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

And this is my post method for login:

public function postLogin(CookieJar $cookieJar, Request $request)
    {

        $this->validate($request, [
           'email1' => 'required|email',
            'password' => 'required|string'
        ]);
        if($user = User::whereEmail($request->email1)->first() ) {
            if(Hash::check($request['password'], $user->getAttributes()['password'])) {

                if(!$user->getAttributes()['is_active']) {
                    return redirect('/login')->withErrors('Your Account is not Activated Yet!');
                } else if($user->getAttributes()['is_deleted']) {
                    return redirect('/login')->withErrors('Your Account is Banned!');
                } else {
                    # Success
                    $cookie = Cookie::make('user_id', $user->getAttributes()['id'], 864000);
                    return redirect('/')->with('message', 'You have Successfully Logged In!')->withCookie($cookie);
                }
            } else {
                return redirect('/login')->withErrors('Your Login Information is Wrong!');
            }
        } else {
            return redirect('/login')->withErrors('Your Login Information is Wrong!');
        }
    }

Please help me.

Added .env file content and postLogin method.

回答1:

You could have a problem with sessions not being saved in your environment. Perhaps do php artisan cache:clear or manually clean and reset priveleges in storage/framework/sessions/ if sessions are saved to file.

I'm assuming you already add the token to your form properly with csrf_token() or something that provides it.