Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

You can use example below to check if authenticated or logged in user has specific access right/roles.


Example


This is just a test so instead of a controller, you can use an event listener as well.


namespace Application\ServerBundle\Controller;

use Application\ServerBundle\Entity\User;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

/**
* @Route("api", service="application_server.controller.api")
*/
class ApiController extends Controller
{
private $authorization;

public function __construct(
AuthorizationCheckerInterface $authorization
) {
$this->authorization = $authorization;
}

/**
* @param Request $request
*
* @Method({"POST"})
* @Route("")
*
* @return Response
*/
public function indexAction(Request $request)
{
$auth = 'Bad';
if ($this->authorization->isGranted('ROLE_ADMIN')) {
$auth = 'Good';
}

.....

return new Response($auth);
}
}

services:
application_server.controller.api:
class: Application\ServerBundle\Controller\ApiController
arguments:
- @security.authorization_checker