【问题标题】:How to disable csrf token for some url in Laravel 4如何在 Laravel 4 中禁用某些 url 的 csrf 令牌
【发布时间】:2017-07-20 21:51:01
【问题描述】:

问题在标题中:How to disable CSRF Token only for some url in Laravel 4?

我知道在 Laravel 5 中使用中间件中的变量 $except 很容易,但在 Laravel 4 中我找不到解决方案...

【问题讨论】:

    标签: laravel token csrf


    【解决方案1】:

    一种方法是扩展 VerifyCsrfToken 并在其中包含一个没有 csrf url 的数组:

    <?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;
        }
    
    }
    

    并更改内核以指向新的中间件:

    protected $middleware = [
    
        ...
    
        'App\Http\Middleware\VerifyCsrfToken',
    ];
    

    您可以在此处找到更多详细信息:

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

    Laravel 5: POST whithout CSRF checking

    【讨论】:

      【解决方案2】:

      您可以通过修改 VerifyCrsfToken.php 类并提供 $openRoutes 来做到这一点,是的,您在接触基类时会玩火。 :)

      //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);
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-22
        • 2018-04-04
        • 1970-01-01
        • 2014-05-17
        • 2022-11-07
        • 2017-09-29
        • 1970-01-01
        • 2013-08-25
        相关资源
        最近更新 更多