@@ -804,6 +804,17 @@ the ``^``) would match ``/admin/foo`` but would also match URLs like ``/foo/admi
804
804
805
805
.. _`book-security-securing-controller` :
806
806
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
+
807
818
Securing Controllers and other Code
808
819
...................................
809
820
@@ -813,8 +824,8 @@ You can easily deny access from inside a controller::
813
824
814
825
public function helloAction($name)
815
826
{
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!' );
818
829
}
819
830
820
831
// ...
@@ -831,6 +842,12 @@ The :method:`Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller::createAcc
831
842
method creates a special :class: `Symfony\\ Component\\ Security\\ Core\\ Exception\\ AccessDeniedException `
832
843
object, which ultimately triggers a 403 HTTP response inside Symfony.
833
844
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
+
834
851
That's it! If the user isn't logged in yet, they will be asked to login (e.g.
835
852
redirected to the login page). If they *are * logged in, they'll be shown
836
853
the 403 access denied page (which you can :ref: `customize <cookbook-error-pages-by-status-code >`).
0 commit comments