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.

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

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据