OAuth 令牌中间件 Slim 版本 3 暂停或退出

OAuth Token Middleware Slim version 3 halt or exit

我正在尝试开发一种简单的身份验证方法。如果用户拥有正确的访问令牌,则应用程序将继续 运行,否则它将退出并显示 401(未授权)状态代码。

我有这样的东西:

api.php

...
$headers = getallheaders();
$auth = new OAuth2Auth($headers, $authconfig);
$app->add($auth, $dbconfig);

$app->post('/user', function($req, $res, $args) {
   //MY CODE ONLY FOR LOGGED IN USERS
});

OAuth2Auth.php

public function __construct($headers, $dbconfig) {
    $this->whiteList = array('\/auth');
    $this->config = $dbconfig;
    $this->headers = $headers;
}

public function __invoke($req, $res, $next) {
   $authHeader = $this->headers['Authorization']; //grabbing the token
   $auth = new AuthService($this->dbconfig); 
   $validated = $auth->verifyOAuth($authHeader); //Verifying Token against DB
   if ($validated){
       $response = $next($request, $response);
   }else{
       //EXIT, STOP or HALT
   }
   return $response;
}

我尝试了多种解决方案来避免中间件继续执行,但没有任何效果。该应用程序始终运行它在 $app->post('/user'...) 中的内容。我已经为 Slim v2 找到了多个解决方案,但到目前为止还没有为 Slim v3 找到任何解决方案。谢谢

与 v2 相比,Slim v3 处理的中间件似乎有点不同。答案是像这样创建我自己的 $response:

public function __invoke($req, $res, $next) {
   $authHeader = $this->headers['Authorization']; //grabbing the token
   $auth = new AuthService($this->dbconfig); 
   $validated = $auth->verifyOAuth($authHeader); //Verifying Token against DB
   if ($validated){
       return $response = $next($request, $response)
                        ->withStatus(200);//OK
   }else{
       return $response->withStatus(403);//Forbidden
   }

}

这对我有帮助 如何使用中间件控制授权流程