TokenMismatchException for API in Laravel 5.2.31

北慕城南 提交于 2019-12-04 03:28:32

问题


What Am I trying?

I already have a website and I am trying Token based authentication for an API in same code and below is the start for sample authentication code

I created a controller below is the code.

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

My route config 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 have posted the request and worked fine if I comment the following line from $middlewareGroups in Kernel.php

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

I have no issues VerifyCsrfToken if I do GET request from POSTMan Extension


回答1:


Open your app\http\Middleware\VerifyCsrfToken.php file.

Here edit $except property with:

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

This will exclude your api routes from CSRF verification.




回答2:


TokenMismatchException generally occurs when csrf token not present in form or expired csrf token or tamperd csrf token.

First:

Make sure you added in form

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

Or

Clear try with clear cache for view files

Or

Check if any redirection are there in flow

Finally if everything fails if you want to customize this error . You can handle this error in hanlers. check [this][1]




回答3:


In your route.php set below code

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

In your kernal.php set below middleware, it is good to use a diffrent middleware for api.

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

Add new middleware ApiAuthenticate.php

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 get and post methods too



来源:https://stackoverflow.com/questions/37383165/tokenmismatchexception-for-api-in-laravel-5-2-31

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!