I am trying to develop a simple authentication method. If the user has the right access token then the app will continue running, otherwise it would exit with a 401 (Unauthorized) status code.
I've got something like this:
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;
}
I have tried multiples solution to avoid the Middleware to continue its execution but nothing works. the app always runs what it's inside $app->post('/user'...). I have found multiples solutions for Slim v2 but nothing so far for Slim v3. Thanks.
It seems like Slim v3 handles a bit different Middleware compared with v2. The answer was to create my own $response like this:
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
}
}
This helped me How to use Middleware to control auth flow