OAuth Token Middleware Slim版本3停止或退出

时间:2017-05-10 12:28:02

标签: php oauth access-token middleware slim-3

我正在尝试开发一种简单的身份验证方法。如果用户具有正确的访问令牌,则应用程序将继续运行,否则将以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还没有。感谢。

1 个答案:

答案 0 :(得分:1)

与v2相比,Slim v3似乎处理了一些不同的中间件。答案是创建我自己的$响应:

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
   }

}

这帮助了我 How to use Middleware to control auth flow