Laravel API TokenMismatchException [英] Laravel API TokenMismatchException
问题描述
我有一个带有发布数据的API调用;假设这是登录过程.
I have an API call with post data; let's say this is the login process.
使用Chrome的Postman扩展程序,我通过POST发送用户名和密码以登录用户. 但我收到了此消息:
With the Postman extension of Chrome I send, via POST, the username and password to log the user in. But I got this message:
Illuminate \ Session \ TokenMismatchException
在我的基本控制器中,我有:
In my Base Controller I have:
/**
* Initializer.
*
* @return void
*/
public function __construct() {
// CSRF Protection
$this->beforeFilter('csrf', array('on' => 'post'));
// Layouts/Notifications
$this->messageBag = new Illuminate\Support\MessageBag;
}
当我使用beforeFilter删除行时,一切正常. 但这不是解决方案. 任何POST调用都会收到此错误消息. 我知道我需要这个_token.但是,当我从API调用时如何获得此令牌?我知道我可以在Laravel内部创建令牌,但是当我通过API从外部调用时该怎么做?
When I delete the row with the beforeFilter everything works fine. But this cannot be a solution. Any POST call would get this error message. I KNOW that I need this _token. But how I get this token when I call from the API? I know that I can create a token inside Laravel, but how can I do this when I call from outside via API?
推荐答案
通常,API用于跨站点请求.因此,您的CSRF保护是毫无意义的.
Generally API's are used for cross site requests. So your CSRF protection is pointless.
如果您不想跨站点使用它,则很有可能API并不是您要执行的操作的最佳解决方案.无论如何,您可以创建一个返回令牌的API端点.
If you're not gonna use it cross-site, chances are that an API is not the optimal solution for what you're trying to do. Anyway, you could make an API endpoint which returns a token.
public function getToken(){
return Response::json(['token'=>csrf_token()]);
}
如果要在某些方法上禁用CSRF保护,则可以使用except
或only
.
$this->beforeFilter('csrf', array('on' => 'post',
'except'=>array('methodName', 'anotherMethod')
));
请参考 Laravel官方文档.
这篇关于Laravel API TokenMismatchException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!