@@ -804,6 +804,17 @@ the ``^``) would match ``/admin/foo`` but would also match URLs like ``/foo/admi
804804
805805.. _`book-security-securing-controller` :
806806
807+
808+ Securing other Services
809+ ~~~~~~~~~~~~~~~~~~~~~~~
810+
811+ In fact, anything in Symfony can be protected using a strategy similar to
812+ the one seen in the previous section. For example, suppose you have a service
813+ (i.e. a PHP class) whose job is to send emails from one user to another.
814+ You can restrict use of this class - no matter where it's being used from -
815+ to users that have a specific role.
816+ >>>>>>> Minor format improvements
817+
807818Securing Controllers and other Code
808819...................................
809820
@@ -813,8 +824,8 @@ You can easily deny access from inside a controller::
813824
814825 public function helloAction($name)
815826 {
816- if (false === $this->get('security.authorization_checker ')->isGranted('ROLE_ADMIN')) {
817- throw $this->createAccessDeniedException();
827+ if (false === $this->get('security.context ')->isGranted('ROLE_ADMIN')) {
828+ throw $this->createAccessDeniedException('Unable to access this page!' );
818829 }
819830
820831 // ...
@@ -831,6 +842,12 @@ The :method:`Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller::createAcc
831842method creates a special :class: `Symfony\\ Component\\ Security\\ Core\\ Exception\\ AccessDeniedException `
832843object, which ultimately triggers a 403 HTTP response inside Symfony.
833844
845+ .. versionadded :: 2.6
846+ You can use directly `$this->isGranted($role) ` instead of
847+ `$this->get('security.context')->isGranted($role) ` to check if
848+ a role is granted and `denyAccessUnlessGranted ` to throw an exception
849+ if the access is not granted (like in the example above).
850+
834851That's it! If the user isn't logged in yet, they will be asked to login (e.g.
835852redirected to the login page). If they *are * logged in, they'll be shown
836853the 403 access denied page (which you can :ref: `customize <cookbook-error-pages-by-status-code >`).
0 commit comments