How to Secure any Service or Method in your Application

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. // src/Newsletter/NewsletterManager.php
  2. // ...
  3. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  4. + use Symfony\Component\Security\Core\Security;
  5. class SalesReportManager
  6. {
  7. + private $security;
  8. + public function __construct(Security $security)
  9. + {
  10. + $this->security = $security;
  11. + }
  12. public function sendNewsletter()
  13. {
  14. $salesData = [];
  15. + if ($this->security->isGranted('ROLE_SALES_ADMIN')) {
  16. + $salesData['top_secret_numbers'] = rand();
  17. + }
  18. // ...
  19. }
  20. // ...
  21. }

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 Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface service. It does the same thing as Security, but allows you to type-hint a more-specific interface.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.