dongyuan3094 2018-05-03 09:14
浏览 174
已采纳

Laravel jwt使用组外的中间件

I'm trying to check and refresh my token on certain api calls, so I've created my own middleware and added it to my Kernel.php $routeMiddleware. Then I added this to the middleware group where I want to check and - if necessary - refresh the token. However, when I login, it also calls this middleware though the login call isn't inside the middleware group, thus I get a 500 error: "The token could not be parsed from the request". I also noticed that the middleware gets called even when removing the 'cors' from the group middleware... Any help would be much appreciated!

This is the code for the middleware:

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        try
        {
            if (! $user = JWTAuth::parseToken()->authenticate() )
            {
                return response()->json(['user_not_found'], 404);
            }
        }
        catch (TokenExpiredException $e)
        {
            try
            {
                $refreshed = JWTAuth::refresh(JWTAuth::getToken());
                $response->header('Authorization', 'Bearer ' . $refreshed);
            }
            catch (JWTException $e)
            {
                return response()->json(['couldnt refresh token'], 404);
            }
            $user = JWTAuth::setToken($refreshed)->toUser();
        }
        catch (JWTException $e)
        {
            return response()->json(['error trying to parse token'], 404);
        }

        Auth::login($user, false);

        return $response;
    }
}

These are my routes:

Route::group(['middleware' => ['api','jwt.auth', 'cors']], function() {
Route::get('logout', 'AuthController@logout');

Route::get('user', 'AuthController@getUser');

Route::get('movies/{page}', 'MovieController@index');
Route::get('movie/{id}', 'MovieController@getMovieByID');
Route::get('movies/search/{string}', 'MovieController@getMovieByTitleGenreDirector');

Route::get('movie/{id}/recommendations', 'MovieController@getMovieRecommendations');
});
  • 写回答

1条回答 默认 最新

  • doob0526 2018-05-03 10:43
    关注

    Oops, seems I forgot to remove the "cors" from my RouteServiceProvider.php

    protected function mapApiRoutes()
    {
        Route::prefix('api')
             ->middleware(['api', 'cors'])
             ->namespace($this->namespace)
             ->group(base_path('routes/api.php'));
    }
    

    It now works as expected.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥15 Stata 面板数据模型选择
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏