Search code examples
phplaravelcsrfcsrf-protection

Converting beforeFilter (4.*) to Middleware (5.*) in Laravel


Recently I've been trying to learn to work with Laravel. Most tutorials are in 4.*, but that's okay. Implementing/converting some deprectated functions are going fine until now. I found out that version 5.* has deprecated the beforeFilter as in:

public function __construct() {
    $this->beforeFilter('csrf', array('on' => ['post', 'put', 'patch', 'delete']));
}

I want to convert this to version 5.*. From what I understand this can be done with Middleware, but I have no idea how I can achieve the same result. I have read the docs, but this didn't really help me understand the topic.

There already is a middleware file called VerifyCsrfToken.php in the app/Http/Middleware folder with this code:

namespace App\Http\Middleware;

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

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        //
    ];
}

Can anyone guide me to set this up and help me understand Middleware a bit better? Thank you.


Solution

  • Because CSRF protection is something that Laravel 5 comes bundled with, this is actually something it checks by default within the Illuminate\Foundation\Http\Middleware\VerifyCsrfToken class that you see being extended in VerifyCsrfToken.php.

    If you have a look in the handle method of that class, you'll see that the first condition that would make the verification successful, calls the isReading method which looks like this:

    /**
     * Determine if the HTTP request uses a ‘read’ verb.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function isReading($request)
    {
        return in_array($request->method(), ['HEAD', 'GET', 'OPTIONS']);
    }
    

    This does the equivalent of what your beforeFilter did in Laravel 4, thus allowing the request to execute for "read" verbs and automatically verifying the token if any other verbs are used, such as post, put, patch, delete.

    If you check the Laravel CSRF Protection Documentation you'll see there's one paragraph that reads:

    You do not need to manually verify the CSRF token on POST, PUT, or DELETE requests. The VerifyCsrfToken HTTP middleware will verify that the token in the request input matches the token stored in the session.

    So there's no more need for you to have that filter. As for understanding how Middleware works in Laravel, reading the entire HTTP Middleware Documentation will do a great job of helping you figure out how it works.