TokenMismatchException for API in Laravel 5.2.31

前端 未结 3 908
南旧
南旧 2021-01-18 15:06

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 auth

相关标签:
3条回答
  • 2021-01-18 15:38

    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.

    0 讨论(0)
  • 2021-01-18 15:40

    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]

    0 讨论(0)
  • 2021-01-18 15:47

    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

    0 讨论(0)
提交回复
热议问题