goldlife
goldlife

Reputation: 1989

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?

Upvotes: 6

Views: 7032

Answers (3)

Matt Komarnicki
Matt Komarnicki

Reputation: 5422

Absolutely don't use this approach.

Open VerifyCsrfToken class and define $except property which will contain an array of routes, where CSRF protection won't be applied.

Example below:

<?php
declare(strict_types=1);

namespace App\Http\Middleware;

use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    protected $except = [
        'api/auth/login',
        'api/*', // this works as well
    ];

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return parent::handle($request, $next);
    }
}

Upvotes: 5

rdiz
rdiz

Reputation: 6176

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.

Upvotes: 10

Sunil
Sunil

Reputation: 95

just listen to this. Just before 30 minute i was facing this same problem. Now it solved. just try this.

Goto App -> HTTP-> Kernel

open the kernel file.

there you can see : \App\Http\Middleware\VerifyCsrfToken::class,

just disable this particular code using //

Thatz it! This will work!

So that you can remove the middleware from the API calling (if you want so..)

Upvotes: 1

Related Questions