Laurvel API TokenMismatchException

I have an API call with post data; let's say this is the login process.

With the Postman extension for Chrome, I send the username and password through POST to log in the user. 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 a line using beforeFilter everything works fine. But this cannot be a solution. Any POST request will receive this error message. I KNOW that I need this. But how do I get this token when I call from the API? I know that I can create a token inside Laravel, but how to do it when I call from outside through the API?

+6
source share
3 answers

In general, APIs are used for cross-site site requests. Therefore, your CSRF protection is pointless.

If you are not going to use a cross site, most likely the API is not the optimal solution for what you are trying to do. In any case, you can create an API endpoint that returns a token.

 public function getToken(){ return Response::json(['token'=>csrf_token()]); } 

If you want to disable CSRF protection for some methods , you can use except or only .

 $this->beforeFilter('csrf', array('on' => 'post', 'except'=>array('methodName', 'anotherMethod') )); 

Refer to the official Laravel documentation .

+9
source

Do not use this approach at all.

Open the VerifyCsrfToken class and define the $except property, which will contain an array of routes where CSRF protection will not 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); } } 
+5
source

just listen to it. Just before 30 minutes I ran into the same problem. Now he has decided. just try this.

Goto App → HTTP-> Kernel

open the kernel file.

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

just disable this specific code using //

It! It will work!

So that you can remove the middleware from the API call (if you want it).

+1
source

Source: https://habr.com/ru/post/980994/


All Articles