Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel API TokenMismatchException

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?

like image 398
goldlife Avatar asked Jan 14 '15 13:01

goldlife


1 Answers

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.

like image 186
rdiz Avatar answered Sep 29 '22 08:09

rdiz