dan-klasson
dan-klasson

Reputation: 14180

Return response from a kernel event listener

I'm using the OAuth2 Server Bundle and I want to authenticate the user for all methods in my controller. It's very similar to the use case done in the documentation How to Setup before and after Filters, except that I want to return the response instead of throwing an exception.

onKernelController with FilterControllerEvent gives me access to the controller so I can access OAuth2 Server Bundle's response method. But I can't return any response in there. I can return a response in onKernelController using GetResponseEvent, but it gets called before onKernelController.

I looked into kernel.exception too but getResponse() returns different error messages so I rather not just throw an ambiguous exception.

What's the best practice for what I am trying to accomplish?

This is my code:

public function onKernelController(FilterControllerEvent $event)
{
    $controller = $event->getController();

    if ($controller[0] instanceof \Foo\Bundle\AuthBundle\Controller\TokenAuthenticatedController) {

        $server = $controller[0]->get('oauth2.server');
        $request = $controller[0]->get('oauth2.request');
        $response = $controller[0]->get('oauth2.response');

        if (!$server->verifyResourceRequest($request, $response)) {
            return $server->getResponse();
        }
    }
}

public function onKernelRequest(GetResponseEvent $event)
{
    $event->setResponse(new Response('Some response', 501));
}

Upvotes: 5

Views: 3651

Answers (2)

nMulot
nMulot

Reputation: 31

This post is a bit dated, but here is the solution for other people who read it.

public function onKernelController(ControllerEvent $event)
{
    // If your condition is met, return a response
    $response = new Response('Your response');
    $event->setController(function () use ($response) {
        return $response;
    });
}

Upvotes: 2

Matteo
Matteo

Reputation: 39380

In the EventListener Approach you can't return a response but you must set it on the event itself.

The problem is that the Event FilterControllerEvent can't manage a returned response, so a better approach is to manage(listen for) the GetResponseForControllerResultEvent where you can set a response and stop the propagation.

Hope this help.

Upvotes: 4

Related Questions