正确设置 Laravel 5 CSRF 令牌的标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27304060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Correctly set headers for Laravel 5 CSRF Token
提问by csduarte
Alright, been searching this one for hours and just can't find the start of a solution.
好吧,已经搜索了几个小时,只是找不到解决方案的开始。
I am using an angularJS frontend with a laravel backend. Restangular is my communcation service.
我正在使用带有 Laravel 后端的 angularJS 前端。Restangular 是我的通讯服务。
My POST are fine, because I can include the _token in the data and it will work.
我的 POST 很好,因为我可以在数据中包含 _token 并且它会起作用。
But for Restangular to call a destroy function it looks like...
但是对于 Restangular 调用销毁函数,它看起来像......
Restangular.all('auth/logout').remove(); //maps to AuthController@Destroy
All fine, but then you will get a TOKENMISMATCH Exception, which is a good security messure
一切都很好,但是你会得到一个 TOKENMISMATCH 异常,这是一个很好的安全措施
Since I can't find a way to include the _token into the remove, since it's body-less essentially, I decided to put the token in the header.
由于我找不到将 _token 包含到删除中的方法,因为它本质上是无正文的,所以我决定将令牌放在标题中。
RestangularProvider.setDefaultHeaders({'X-XSRF-TOKEN': CSRF_TOKEN}); //CSRF_TOKEN gathered elsewhere
Out of the Chrome dev tolos, I can see the header is set to
在 Chrome dev tolos 之外,我可以看到标题设置为
X-XSRF-TOKEN:ClkQIRLpFQgMg8ZT6X5CF6doCplRfdJzW8msx2JI
X-XSRF-TOKEN is exactlywhat the VerifyCrsfToken.php is looking for. Yet, it spits out a decrypt error. Any other token name, such as XSRF-TOKEN, _TOKEN, CSRF_TOKEN all spit out token mismatch.
X-XSRF-TOKEN正是VerifyCrsfToken.php 正在寻找的东西。然而,它吐出一个解密错误。任何其他令牌名称,例如 XSRF-TOKEN、_TOKEN、CSRF_TOKEN 都会吐出令牌不匹配。
Because of that last fact, it seems like the header is declared correctly, but something beyond my comprehension is causing Laravel to fail the decrypt. And I've closely at the decrypt function, but don't understand why it'd fail...
由于最后一个事实,似乎标头已正确声明,但超出我理解范围的事情导致 Laravel 无法解密。我已经密切关注解密功能,但不明白为什么它会失败......
Thank you for your help.
感谢您的帮助。
回答by tiran
This is due to encryption of the csrf token. Laravel expect the token to be encrypted.
这是由于 csrf 令牌的加密。Laravel 期望令牌被加密。
It tries to decrypt the the plain token you provide and it fails.
它尝试解密您提供的普通令牌,但失败了。
Before you can use the token in the header you have to encrypt it.
在您可以使用标头中的令牌之前,您必须对其进行加密。
$encrypter = app('Illuminate\Encryption\Encrypter');
$encrypted_token = $encrypter->encrypt(csrf_token());
That did the trick for me.
那对我有用。
Alex
亚历克斯
回答by Modder
For Laravel 5, no needto add CSRF token to Angular http headers.
对于 Laravel 5,无需将 CSRF 令牌添加到 Angular http 标头。
Laravel 5 with Angular do this automatically for you.
带有 Angular 的 Laravel 5 会自动为您执行此操作。