Handling expired token in Laravel

后端 未结 13 2793
情话喂你
情话喂你 2020-11-29 00:30

What is the best way to handle expired tokens in laravel 5.

I mean I have a page and it has some links which perform ajax requests. They work fine when the page is

13条回答
  •  误落风尘
    2020-11-29 01:21

    I combine 2 things for this case:

    1. Increase session lifetime

    //In config/session.php replace this:
    
    'lifetime' => 120
    
    //with:
    
    'lifetime' => 360
    

    Laravel 5 default lifetime is 120 (minutes), you can change it to whatever value you like, for example 360 (6 hours)

    2. Catch the exception and display an error message

    //In app/Exceptions/Handler.php replace this:
    
    public function render($request, Exception $e)
    {
        if ($e instanceof ModelNotFoundException) {
            $e = new NotFoundHttpException($e->getMessage(), $e);
        }
    
        return parent::render($request, $e);
    }
    
    //with:
    
    public function render($request, Exception $e)
    {
        if ($e instanceof ModelNotFoundException) {
            $e = new NotFoundHttpException($e->getMessage(), $e);
        }
    
        if ($e instanceof \Illuminate\Session\TokenMismatchException) {            
            return redirect('/')->withErrors(['token_error' => 'Sorry, your session seems to have expired. Please try again.']);
        }
    
        return parent::render($request, $e);
    }
    

    So basicaly you redirect the user to the root "/" (you can change this to any path you want) with an error message and on that page you have to do this to display the error message:

    @if ($errors->has('token_error'))
        {{ $errors->first('token_error') }}
    @endif
    

提交回复
热议问题