簡體   English   中英

如何在Laravel 4中為某些URL禁用CSRF令牌

[英]How to disable csrf token for some url in Laravel 4

問題在標題中:如何僅對Laravel 4中的某些URL禁用CSRF令牌?

我知道在Laravel 5中使用變量$ except在中間件中很容易,但是在Laravel 4中我找不到解決方案...

一種方法是擴展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:沒有CSRF檢查的POST

您可以通過修改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);
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM