Laravel CSRF Protection

官方文档:https://laravel.com/docs/5.5/csrf

客户端请求设置

表单添加隐藏域

1
2
3
4
<form method="POST" action="/profile">
{{ csrf_field() }}
...
</form>

AJAX设置

1
2
3
4
5
6
7
<meta name="csrf-token" content="{{ csrf_token() }}">

$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

设置排除CSRF认证的路由

app/Http/Middleware/VerifyCsrfToken.php

1
2
3
4
5
6
7
8
9
10
11
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
'/api/*',
];
}

关闭CSRF认证

Laravel默认是开启了CSRF功能,需要关闭此功能有两种方法:

方法一

打开文件:app\Http\Kernel.php,把这行注释掉:

1
'App\Http\Middleware\VerifyCsrfToken'

方法二

打开文件:app\Http\Middleware\VerifyCsrfToken.php,修改为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php namespace App\Http\Middleware;

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

class VerifyCsrfToken extends BaseVerifier {

/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// 使用CSRF
//return parent::handle($request, $next);
// 禁用CSRF
return $next($request);
}

}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :