Question

I'm getting this TokenMismatchException with Laravel 4. It happens to me if the browser sits on the login page for a while. For example a lot of times when I come back to work on my project the next day, if my browser has the login page open in a tab, when I try to log in I get the TokenMismatchException. If I'm logging in and out throughout the day while working, I never see it. It's like the token expires or something.

Route.php

  // route to show the admin login form
Route::get('login', array('uses' => 'AdminController@showLogin'));

// route to process the admin login form
Route::post('login', array('uses' => 'AdminController@doLogin'));

AdminController.php

   public function showLogin()
{
    // show the login form
    return View::make('admin.login');
}



public function doLogin()
{
    // validate the info, create rules for the inputs
    $rules = array('username' => 'required','password' => 'required' );

    // run the validation rules on the inputs from the form
    $validator = Validator::make(Input::all(), $rules);

    // if the validator fails, redirect back to the form
    if ($validator->fails()) {
        return Redirect::to('login')
            ->withErrors($validator) // send back all errors to the login form
            ->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form
    } else {


        // create our user data for the authentication
        $userdata = array('my_username'=> Input::get('username'),'password'=> Input::get('password'));



        // attempt to do the login
        if (Auth::attempt($userdata)) {

            return Redirect::intended('dashboard');


        } else {        

            // Authentication not successful, send back to form 
            return Redirect::to('login')->with('message', 'Your username/password combination was incorrect');

        }

    }
}

Please, help is needed...

Was it helpful?

Solution

That's normal, session will expire if you get idle for too long. It's a security measure, so you just need to make sure you redirect your user to login when the token expires. Add this to your global.php file or create a exceptions.php file to it:

App::error(function(\Illuminate\Session\TokenMismatchException $exception)
{
    return Redirect::route('login')->with('message','Your session has expired. Please try logging in again.');
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top