正确设置Laravel 5 CSRF令牌的标头 [英] Correctly set headers for Laravel 5 CSRF Token

查看:164
本文介绍了正确设置Laravel 5 CSRF令牌的标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,已经搜索了一个小时,只是找不到解决方案的开始.

Alright, been searching this one for hours and just can't find the start of a solution.

我正在使用带有laravel后端的angularJS前端.我的通讯服务是Restangular.

I am using an angularJS frontend with a laravel backend. Restangular is my communcation service.

我的POST很好,因为我可以在数据中包含_token,它将起作用.

My POST are fine, because I can include the _token in the data and it will work.

但是,让Restangular调用destroy函数时,它看起来就像...

But for Restangular to call a destroy function it looks like...

Restangular.all('auth/logout').remove(); //maps to AuthController@Destroy

很好,但是随后您将得到一个TOKENMISMATCH异常,这是一个很好的安全信息

All fine, but then you will get a TOKENMISMATCH Exception, which is a good security messure

由于我找不到将_token包含在remove中的方法,因为它实质上没有主体,所以我决定将令牌放在标头中.

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.

RestangularProvider.setDefaultHeaders({'X-XSRF-TOKEN': CSRF_TOKEN}); //CSRF_TOKEN gathered elsewhere

在Chrome开发者圈中,我可以看到标头设置为

Out of the Chrome dev tolos, I can see the header is set to

X-XSRF-TOKEN:ClkQIRLpFQgMg8ZT6X5CF6doCplRfdJzW8msx2JI

X-XSRF-TOKEN 完全是VerifyCrsfToken.php所寻找的.但是,它会吐出解密错误.其他任何令牌名称,例如XSRF-TOKEN,_TOKEN,CSRF_TOKEN都吐出令牌不匹配.

X-XSRF-TOKEN is exactly what 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.

由于最后一个事实,似乎标头已正确声明,但是超出我的理解范围的原因导致Laravel解密失败.而且我一直在使用解密功能,但是不明白为什么它会失败...

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...

感谢您的帮助.

推荐答案

这是由于对csrf令牌进行了加密. Laravel希望令牌可以被加密.

This is due to encryption of the csrf token. Laravel expect the token to be encrypted.

它尝试解密您提供的普通令牌,但失败.

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());

那对我有用.

亚历克斯

这篇关于正确设置Laravel 5 CSRF令牌的标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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