I have an API call with post data; let's say this is the login process.
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;
}
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?
Generally API's are used for cross site requests. So your CSRF protection is pointless.
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()]);
}
If you want to disable CSRF-protection on some methods, you could use except
or only
.
$this->beforeFilter('csrf', array('on' => 'post',
'except'=>array('methodName', 'anotherMethod')
));
Please refer to the official Laravel documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With