K4tn1x
K4tn1x

Reputation: 133

How to disable csrf token for some url in Laravel 4

The question is in the title : How to disable CSRF Token only for some url in Laravel 4 ?

I know in Laravel 5 it's easy with the variable $except in the middleware but in Laravel 4 I don't find the solution...

Upvotes: 0

Views: 1157

Answers (2)

Manish
Manish

Reputation: 3643

One way is to extend the VerifyCsrfToken and have an array of no csrf urls inside :

<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Session\TokenMismatchException;

class VerifyCsrfToken extends \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken {

    protected $except_urls = [
        'contact/create',
        'contact/update',
        ...
    ];

    public function handle($request, Closure $next)
    {
        $regex = '#' . implode('|', $this->except_urls) . '#';

        if ($this->isReading($request) || $this->tokensMatch($request) || preg_match($regex, $request->path()))
        {
            return $this->addCookieToResponse($request, $next($request));
        }

        throw new TokenMismatchException;
    }

}

And change in Kernel to point the new middleware :

protected $middleware = [

    ...

    'App\Http\Middleware\VerifyCsrfToken',
];

You can find more details at there:

https://laravel.com/docs/5.1/routing#csrf-protection

Laravel 5: POST whithout CSRF checking

Upvotes: 1

Rahi
Rahi

Reputation: 1485

You can do this by modifying VerifyCrsfToken.php class and by providing $openRoutes and yes you will be playing with fire when touching base classes. :)

//app/Http/Middleware/VerifyCsrfToken.php

//add an array of Routes to skip CSRF check
private $openRoutes = ['free/route', 'free/too'];

//modify this function
public function handle($request, Closure $next)
    {
        //add this condition 
    foreach($this->openRoutes as $route) {

      if ($request->is($route)) {
        return $next($request);
      }
    }

    return parent::handle($request, $next);
  }

Upvotes: 0

Related Questions