E1.33 Php Symfony Security: Role based controller protection (Wpf, Xamarin, Angular SPA, Reactjs SPA) - chempkovsky/CS2WPF-and-CS2XAMARIN GitHub Wiki

One declarative way

One of the way to protect controllers is to use access_control of the security.yaml

With a code

  • To protect by only one role
    • put the following line at the beginning of each method
  $this->denyAccessUnlessGranted('ROLE_ADMIN');
  • To protect by multiple roles
    • put the following line at the beginning of each method (User must have at least one of the roles)
  if(!($this->isGranted('ROLE_ADMIN') || $this->isGranted('ROLE_EMP'))) {
         $exception = $this->createAccessDeniedException('This is your message here');
         //   $exception->setAttributes($attribute);
         //   $exception->setSubject($subject);
         throw $exception;
  }
  • To protect by multiple roles
    • put the following line at the beginning of each method. (User must have two roles)
  if(!($this->isGranted('ROLE_ADMIN') && $this->isGranted('ROLE_EMP'))) {
         $exception = $this->createAccessDeniedException('This is your message here');
         //   $exception->setAttributes($attribute);
         //   $exception->setSubject($subject);
         throw $exception;
  }