TokenMismatchException for API in Laravel 5.2.31

What am I trying to do?

I already have a website and am trying to authenticate a token for an API in the same code, and below is an example authentication code

I created the controller below - this is the code.

class AccountController extends \App\Http\Controllers\Controller { public function apilogin($UserData) { return json_decode($UserData); } } 

My route configuration is below.

 Route::group(['prefix' => 'api/v1', 'middleware' => 'auth.api'], function () { Route::post('/apilogin', 'API\User\Account\AccountController@apilogin'); }); 

** Then, from the Postman Chrome Extension, I sent a request and worked perfectly if you comment on the next line from $ middlewareGroups in Kernel.php

 \App\Http\Middleware\VerifyCsrfToken::class, 

I have no VerifyCsrfToken problems if I make a GET request from the POSTMan extension

+4
php laravel laravel-5
May 23 '16 at 5:26
source share
3 answers

Open the app\http\Middleware\VerifyCsrfToken.php .

Here, edit the $except property with:

 protected $except = [ 'api/*' ]; 

This excludes your api routes from CSRF checking.

+7
May 25 '16 at 2:27
source share

In your route.php file below

 Route::group(['prefix' => API_PREFIX,'middleware' => 'auth.api'], function() { // Your Route } 

In your kernal.php file below the middleware, it is useful to use various middleware for api.

 'auth.api' => \App\Http\Middleware\ApiAuthenticate::class, 

Add New ApiAuthenticate.php Middleware

 class ApiAuthenticate { public function handle($request, Closure $next, $guard = 'api') { if (\Auth::guard($guard)->guest()) { return response("Invalid user"); } else { return $next($request); } return $next($request); } } 

Check your receiving and publishing methods.

0
May 23 '16 at 5:48
source share

TokenMismatchException usually occurs when the csrf token is not present in the expired csrf form or token tsperd csrf.

Firstly:

Make sure you add to the form

 <input type="hidden" name="_token" value="{{ csrf_token() }}"> 

Or

Clear attempt with clear cache for view files

Or

Check for redirects in the stream

Finally, if all fails, if you want to configure this error. You can handle this error in hanlers. check out [this][1]

0
May 23 '16 at 6:07 a.m.
source share



All Articles