Laravel Passport将中间件添加到默认的身份验证/令牌路由

时间:2018-03-25 15:24:57

标签: php laravel

我正在尝试构建一个多租户应用程序并在我的中间件中的数据库之间切换

所以我有以下中间件

    public function handle($request, Closure $next)
{
    //check if request has the value of header
    $passedheader = $request->header('HTTP_X_APP_LOCATION');

    $headers = AppConnectionsModel::get()->pluck('header_val')->toArray();

    if(!isset($passedheader) || !in_array($passedheader,$headers)){
        return response('Invalid Request.', 403);
    }

    //get the actual header passed
    $connection = AppConnectionsModel::where('header_val',$passedheader)->first();
    if($connection){
        Config::set('database.connections.tennant.database', $connection->database);
        Config::set('database.connections.tennant.port', $connection->port);
        Config::set('database.connections.tennant.username', $connection->username);
        Config::set('database.connections.tennant.password', $connection->password);
        Config::set('database.connections.tennant.host', $connection->host);


       return $next($request);

    }else{
        return response("Invalid Request.", 200);
    }

    return $next($request);
}

所以基本上中间件的作用是检查连接设置并设置为配置

所以我想将此中间件应用于oauth/token的护照令牌路由,以便每次用户发送获取令牌的请求时都会使用他或她的数据库

在我的用户模型中我有

protected $connection = "tennant";
protected $table = "tbl_user";

如何覆盖laravel中的oauth / token护照路径以使用此中间件

如下所述,我也尝试在内核文件中更改中间件优先级,如

  protected $routeMiddleware = [
    'appconnection' => \App\Http\Middleware\AppConnectionMiddleware::class,
    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'role' => \Zizaco\Entrust\Middleware\EntrustRole::class,
    'permission' => \Zizaco\Entrust\Middleware\EntrustPermission::class,
    'ability' => \Zizaco\Entrust\Middleware\EntrustAbility::class,

];

应用程序连接是我们放在顶部的中间件,上面显示了句柄方法但是它没有在护照oauth / token路由之前执行

检查我的配置护照路线设置在AuthServiceProvider喜欢

 class AuthServiceProvider extends ServiceProvider
  {
  protected $policies = [
      'App\Model' => 'App\Policies\ModelPolicy',
  ];

/**
 * Register any authentication / authorization services.
 *
 * @return void
 */
public function boot()
{
    $this->registerPolicies();
    Passport::routes();
    //
}

}

1 个答案:

答案 0 :(得分:1)

您需要在Kernel.php文件中添加一个数组。

protected $middlewarePriority = [
    \App\Http\Middleware\AppConnectionMiddleware::class,
    \Laravel\Passport\Http\Middleware\CheckClientCredentials::class
];

请这样做,看看它应该有用。

护照路线

Route::group(['middleware'=>'appconnection'], function(){ 
    Passport::routes(); 
});