We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Implementing Middleware Authentication

I am attempting to create a REST API with oAuth2 Authentication. I am using ThePHPLeague and Sumeko's libraries and have it set up to a point where I am comfortable going forward in regards to that. My question however is how to implement that without having redundant code.

The way that I thought was best was to take advantage of middleware events. I added the validation to the \Micro before() method and it seems to work generally. The problem is that when they get the token wrong I am only seemingly able to pass false and not change the headers to 403 and send a message. Or, at least I am not understanding how to do this, as I am very new to Phalcon.

This is my current code:

$app->before(function() use ($app) {
    try {
        $app->resource->setTokenKey('token');
        $app->resource->isValid();
        return true;
    } catch (League\OAuth2\Server\Exception\InvalidAccessTokenException $e) {
        $body['meta'] = array(
            'error'   => TRUE,
            'status'  => 403,
            'message' => $e->getMessage()
        );
        $app->response
            ->setStatusCode(403, 'Forbidden')
            ->setContentType('application/json')
            ->setJsonContent(array(
                'error'   => TRUE,
                'status'  => 403,
                'message' => $e->getMessage()
        ));
        return false;
    }
});

But all it returns is a 200 OK response, and that definitely is not what I want.



98.8k
Accepted
answer

Try adding:

$app->response->sendHeaders();

or

$app->response->send();

before return false;

This worked for me, thank you. If you could somehow add this to documentation I think that it would be useful to a lot of people; it is such a minor thing that was overlooked.

Thank you!

Try adding:

$app->response->sendHeaders();

or

$app->response->send();

before return false;