How to Secure any Service or Method in your Application

In the security article, you learned how to secure a controller via a shortcut method.

But, you can check access anywhere in your code by injecting the Security service. For example, suppose you have a SalesReportManager service and you want to include extra details only for users that have a ROLE_SALES_ADMIN role:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// src/Newsletter/NewsletterManager.php

// ...
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
+ use Symfony\Component\Security\Core\Security;

class SalesReportManager
{
+     private $security;

+     public function __construct(Security $security)
+     {
+         $this->security = $security;
+     }

    public function sendNewsletter()
    {
        $salesData = [];

+         if ($this->security->isGranted('ROLE_SALES_ADMIN')) {
+             $salesData['top_secret_numbers'] = rand();
+         }

        // ...
    }

    // ...
}

If you’re using the default services.yaml configuration, Symfony will automatically pass the security.helper to your service thanks to autowiring and the Security type-hint.

You can also use a lower-level AuthorizationCheckerInterface service. It does the same thing as Security, but allows you to type-hint a more-specific interface.