This is the last article from the custom software development series of posts dedicated to shed a light on modern web application development using PHP and Symfony web framework.
In this article we’ll try to restrict the access to our API and in order to do that we have to regard additional capabilities, provided by the Symfony framework.
Our goal will be the implementation of the mechanism dedicated to restrict the access to the specific method of the controller. That will be the simplest example of the authorization mechanism.
Let’s try to recall the material from the previous article. As such we already have the controller, that returns the anticipated response to the HTTP request.
Once we skip the business logic - as it isn’t of the importance for our example - the controller looks like:
Above the method there is the comments block, all the comments have to be familiar to us. We’ve already discussed that comments of such kind are annotations and because of that they define the additional logic or restrictions - enhance the contract of the controller method.
Let’s introduce our own annotation @GrantAll(). The idea of it is to restrict the invocation of the controller method only if that controller method had the mentioned annotation.
Thus, let’s add the annotation to the comments block:
As for now, the annotation that we have specified is simply the comment and it doesn’t restrict or allows anything yet.
But let’s proceed and make that annotation work. So, we would like to allow controller’s method invocation only if there is the @GrantAll() annotation declared.
How do we go about that?
Symfony has the EventDispatcher component that implements the Mediator pattern and is the central point, where the event can be published by one component and leads to the receiving of that event by other component.
Evenmore, the dispatcher allows for other components to handle the standard Symfony events - and thus to register the specific class / method to listen and handle those.
As the result, we create the class / method with the custom logic and ask dispatcher to call it once the event is emitted.
The comprehensive list of events, emitted by Symfony, can be found in documentation. However, we are more interesting in such event as kernel.controller.
This event occurs before the controller invocation, any controller, always. Thus, we have to create the Handler for kernel.controller event, then that handler has to check, whether the method of our controller has the corresponding annotation indeed and based on that to take a decision, whether to allow or deny the access.
At first, let’s create the definition of out annotation: