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 {
        return true;
    } catch (League\OAuth2\Server\Exception\InvalidAccessTokenException $e) {
        $body['meta'] = array(
            'error'   => TRUE,
            'status'  => 403,
            'message' => $e->getMessage()
            ->setStatusCode(403, 'Forbidden')
                '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.


Try adding:




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:

```php $app->response->sendHeaders(); ```


```php $app->response->send(); ```

before return false;