CSRF 保护
这是一篇协同翻译的文章,你可以点击『我来翻译』按钮来参与翻译。
CSRF Protection
Introduction
Cross-site request forgeries are a type of malicious exploit whereby unauthorized commands are performed on behalf of an authenticated user. Thankfully, Laravel makes it easy to protect your application from cross-site request forgery (CSRF) attacks.
An Explanation of the Vulnerability
In case you're not familiar with cross-site request forgeries, let's discuss an example of how this vulnerability can be exploited. Imagine your application has a /user/email
route that accepts a POST
request to change the authenticated user's email address. Most likely, this route expects an email
input field to contain the email address the user would like to begin using.
Without CSRF protection, a malicious website could create an HTML form that points to your application's /user/email
route and submits the malicious user's own email address:
<form action="https://your-application.com/user/email" method="POST">
<input type="email" value="malicious-email@example.com">
</form>
<script>
document.forms[0].submit();
</script>
If the malicious website automatically submits the form when the page is loaded, the malicious user only needs to lure an unsuspecting user of your application to visit their website and their email address will be changed in your application.
To prevent this vulnerability, we need to inspect every incoming POST
, PUT
, PATCH
, or DELETE
request for a secret session value that the malicious application is unable to access.
阻止 CSRF 请求
Laravel 会自动为应用程序管理的每个活动 用户会话 生成一个 CSRF 「令牌」。此令牌用于验证经过身份验证的用户是否是实际向应用程序发出请求的人。由于此令牌存储在用户的会话中,并且每次重新生成会话时都会发生变化,因此恶意应用程序无法访问它。
当前会话的 CSRF 令牌可以通过请求的会话或 csrf_token
辅助函数来访问:
use Illuminate\Http\Request;
Route::get('/token', function (Request $request) {
$token = $request->session()->token();
$token = csrf_token();
// ...
});
每当你在应用程序中定义 POST
、 PUT
、 PATCH
或 DELETE
HTML 表单时,都应该在表单中包含一个隐藏的 CSRF _token
字段,以便 CSRF 保护中间件可以验证请求。为了方便起见,你可以使用 @csrf
Blade 指令来生成隐藏令牌输入字段:
<form method="POST" action="/profile">
@csrf
<!-- Equivalent to... -->
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
</form>
默认情况下包含在 web
中间件组中的 Illuminate\Foundation\Http\Middleware\ValidateCsrfToken
中间件 将自动验证请求输入中的令牌是否与会话中存储的令牌匹配。当这两个令牌匹配时,我们就知道经过身份验证的用户是发起请求的用户。
CSRF Tokens & SPAs
如果你正在构建使用 Laravel 作为 API 后端的 SPA,则应查阅 Laravel Sanctum 文档,了解有关使用 API 进行身份验证和防范 CSRF 漏洞的信息。
Excluding URIs From CSRF Protection
Sometimes you may wish to exclude a set of URIs from CSRF protection. For example, if you are using Stripe to process payments and are utilizing their webhook system, you will need to exclude your Stripe webhook handler route from CSRF protection since Stripe will not know what CSRF token to send to your routes.
Typically, you should place these kinds of routes outside of the web
middleware group that Laravel applies to all routes in the routes/web.php
file. However, you may also exclude specific routes by providing their URIs to the validateCsrfTokens
method in your application's bootstrap/app.php
file:
->withMiddleware(function (Middleware $middleware) {
$middleware->validateCsrfTokens(except: [
'stripe/*',
'http://example.com/foo/bar',
'http://example.com/foo/*',
]);
})
[!NOTE]
For convenience, the CSRF middleware is automatically disabled for all routes when running tests.
X-CSRF-TOKEN
In addition to checking for the CSRF token as a POST parameter, the Illuminate\Foundation\Http\Middleware\ValidateCsrfToken
middleware, which is included in the web
middleware group by default, will also check for the X-CSRF-TOKEN
request header. You could, for example, store the token in an HTML meta
tag:
<meta name="csrf-token" content="{{ csrf_token() }}">
Then, you can instruct a library like jQuery to automatically add the token to all request headers. This provides simple, convenient CSRF protection for your AJAX based applications using legacy JavaScript technology:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
X-XSRF-TOKEN
Laravel stores the current CSRF token in an encrypted XSRF-TOKEN
cookie that is included with each response generated by the framework. You can use the cookie value to set the X-XSRF-TOKEN
request header.
This cookie is primarily sent as a developer convenience since some JavaScript frameworks and libraries, like Angular and Axios, automatically place its value in the X-XSRF-TOKEN
header on same-origin requests.
[!NOTE]
By default, theresources/js/bootstrap.js
file includes the Axios HTTP library which will automatically send theX-XSRF-TOKEN
header for you.
本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。
推荐文章: