Laravel 5禁用和排除单个路径的CSRF

时间:2015-11-14 17:45:51

标签: laravel-5

我正在尝试为ajax请求排除和禁用CSRF,例如:

$('[id^="change_user_status_account-"]').click(function () {
    var id = $(this).attr('id').split('-');
    $.ajax({
        type: "POST",
        url: "{{ URL::route('changeUserStatusAccount') }}",
        data: {user_id: id[1]},
        success: function (data) {
        }
    });
    return false;
});

排除CSRF路由的changeUserStatusAccount

protected $except = [
    '/changeUserStatusAccount',
];

我的路线:

Route::any('changeUserStatusAccount',  ['as'=>'changeUserStatusAccount','middleware' => 'csrf', function() {
        \DB::table('users')
            ->where('id', Request::input('user_id'))
            ->update(['status' => $info->status == 1 ? 0 : 1]);
        return 1;
}]);

我在firebug中得到错误500并且这不能正常工作

2 个答案:

答案 0 :(得分:2)

VerifyCsrfToken执行此操作:

private $openRoutes = ['YOUR_OPEN_ROUTE/*'];

public function handle($request, Closure $next)
{

    foreach($this->openRoutes as $route) {

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

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

答案 1 :(得分:1)

只需添加数组$中的路由,除了app / Http / Middleware / VerifyCsrfToken.php,这项工作在Laravel 5.1中

<?php

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 = [
        'changeUserStatusAccount',
        'changeUserStatusAccount/*
    ];
}

来自文档:http://laravel.com/docs/5.1/routing#csrf-excluding-uris