Laravel 5.3 POST和tokenmismatch [英] Laravel 5.3 POST and tokenmismatch

查看:227
本文介绍了Laravel 5.3 POST和tokenmismatch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面,我希望发送一个POST来触发数据库更新。该请求将来自另一个站点。

I have a page that I want to have a POST sent to which will trigger a database update. The request will come from another site.

Route::post('update', 'DatabaseController@update');

该请求包含一个元素

(原始)

id=12345

(表格数据)

id: 12345

每当我访问该页面时,都会收到此错误

Whenever I access the page, I get this error

TokenMismatchException in VerifyCsrfToken.php line 68:


推荐答案

Laravel可以轻松保护您的应用程序免受跨站点请求伪造(CSRF)攻击。跨站点请求伪造是一种恶意利用,其中代表经过身份验证的用户执行未经授权的命令。

Laravel makes it easy to protect your application from cross-site request forgery (CSRF) attacks. Cross-site request forgeries are a type of malicious exploit whereby unauthorized commands are performed on behalf of an authenticated user.

Laravel自动为每个活动用户生成CSRF令牌由应用程序管理的会话。此令牌用于验证经过身份验证的用户是否是实际向应用程序发出请求的用户。

Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually making the requests to the application.

无论何时在应用程序中定义HTML表单,都应包含表单中隐藏了CSRF令牌字段,以便CSRF保护中间件可以验证请求。您可以使用csrf_field帮助程序生成令牌字段:

Anytime you define a HTML form in your application, you should include a hidden CSRF token field in the form so that the CSRF protection middleware can validate the request. You may use the csrf_field helper to generate the token field:

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

除了检查CSRF令牌作为POST参数之外,VerifyCsrfToken中间件还将检查X-CSRF-TOKEN请求标头。例如,您可以将令牌存储在HTML元标记中:

In addition to checking for the CSRF token as a POST parameter, the VerifyCsrfToken middleware will also check for the X-CSRF-TOKEN request header. You could, for example, store the token in a HTML meta tag:

<meta name="csrf-token" content="{{ csrf_token() }}">

然后,一旦创建了元标记,就可以指示像jQuery这样的库自动添加令牌到所有请求标头。这为基于AJAX的应用程序提供了简单,方便的CSRF保护:

Then, once you have created the meta tag, 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:

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

参考

注意:要从CSRF验证中排除某些URI,请转到项目/ app / Http / Middleware ,打开文件 VerifyCsrfToken.php 并传递你的网址:

Note: To exclude some URI's from CSRF verification go to project/app/Http/Middleware, open the file VerifyCsrfToken.php and pass your url like:

protected $except = [
    '/api/authuser',
];

此数组中传递的网址从CSRF验证的URI中排除。

the url passed in this array are excluded from URI's from CSRF verification.

这篇关于Laravel 5.3 POST和tokenmismatch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆