Skip to content

Commit c208e53

Browse files
committed
minor #9847 Use the new Security helper in some code examples (javiereguiluz)
This PR was squashed before being merged into the 3.4 branch (closes #9847). Discussion ---------- Use the new Security helper in some code examples This fixes #8437 replacing `use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;` by `use Symfony\Component\Security\Core\Security;` when possible. Also, replace `use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;` by `use Symfony\Component\Security\Core\Security;` when possible. Commits ------- df21fd8 Use the new Security helper in some code examples
2 parents aa0cd7d + df21fd8 commit c208e53

File tree

7 files changed

+77
-72
lines changed

7 files changed

+77
-72
lines changed

controller/argument_value_resolver.rst

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -99,16 +99,15 @@ retrieved from the token storage::
9999
use Symfony\Component\HttpFoundation\Request;
100100
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
101101
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
102-
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
103-
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
102+
use Symfony\Component\Security\Core\Security;
104103

105104
class UserValueResolver implements ArgumentValueResolverInterface
106105
{
107-
private $tokenStorage;
106+
private $security;
108107

109-
public function __construct(TokenStorageInterface $tokenStorage)
108+
public function __construct(Security $security)
110109
{
111-
$this->tokenStorage = $tokenStorage;
110+
$this->security = $security;
112111
}
113112

114113
public function supports(Request $request, ArgumentMetadata $argument)
@@ -117,27 +116,20 @@ retrieved from the token storage::
117116
return false;
118117
}
119118

120-
$token = $this->tokenStorage->getToken();
121-
122-
if (!$token instanceof TokenInterface) {
123-
return false;
124-
}
125-
126-
return $token->getUser() instanceof User;
119+
return $this->security->getUser() instanceof User;
127120
}
128121

129122
public function resolve(Request $request, ArgumentMetadata $argument)
130123
{
131-
yield $this->tokenStorage->getToken()->getUser();
124+
yield $this->security->getUser();
132125
}
133126
}
134127

135128
In order to get the actual ``User`` object in your argument, the given value
136129
must fulfill the following requirements:
137130

138131
* An argument must be type-hinted as ``User`` in your action method signature;
139-
* A security token must be present;
140-
* The value must be an instance of the ``User``.
132+
* The value must be an instance of the ``User`` class.
141133

142134
When all those requirements are met and ``true`` is returned, the
143135
``ArgumentResolver`` calls ``resolve()`` with the same values as it called

form/dynamic_form_modification.rst

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,6 @@ Using an event listener, your form might look like this::
212212
use Symfony\Component\Form\FormBuilderInterface;
213213
use Symfony\Component\Form\FormEvents;
214214
use Symfony\Component\Form\FormEvent;
215-
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
216215
use Symfony\Component\Form\Extension\Core\Type\TextType;
217216
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
218217

@@ -236,28 +235,30 @@ contains only this user's friends.
236235
Luckily it is pretty easy to inject a service inside of the form. This can be
237236
done in the constructor::
238237

239-
private $tokenStorage;
238+
use Symfony\Component\Security\Core\Security;
239+
// ...
240+
241+
private $security;
240242

241-
public function __construct(TokenStorageInterface $tokenStorage)
243+
public function __construct(Security $security)
242244
{
243-
$this->tokenStorage = $tokenStorage;
245+
$this->security = $security;
244246
}
245247

246248
.. note::
247249

248-
You might wonder, now that you have access to the User (through the token
249-
storage), why not just use it directly in ``buildForm()`` and omit the
250-
event listener? This is because doing so in the ``buildForm()`` method
251-
would result in the whole form type being modified and not just this
252-
one form instance. This may not usually be a problem, but technically
253-
a single form type could be used on a single request to create many forms
254-
or fields.
250+
You might wonder, now that you have access to the User, why not just use it
251+
directly in ``buildForm()`` and omit the event listener? This is because
252+
doing so in the ``buildForm()`` method would result in the whole form type
253+
being modified and not just this one form instance. This may not usually be
254+
a problem, but technically a single form type could be used on a single
255+
request to create many forms or fields.
255256

256257
Customizing the Form Type
257258
~~~~~~~~~~~~~~~~~~~~~~~~~
258259

259-
Now that you have all the basics in place you can take advantage of the ``TokenStorageInterface``
260-
and fill in the listener logic::
260+
Now that you have all the basics in place you can use the features of the
261+
security helper to fill in the listener logic::
261262

262263
// src/AppBundle/Form/Type/FriendMessageFormType.php
263264

@@ -266,16 +267,16 @@ and fill in the listener logic::
266267
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
267268
use Symfony\Component\Form\Extension\Core\Type\TextType;
268269
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
269-
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
270+
use Symfony\Component\Security\Core\Security;
270271
// ...
271272

272273
class FriendMessageFormType extends AbstractType
273274
{
274-
private $tokenStorage;
275+
private $security;
275276

276-
public function __construct(TokenStorageInterface $tokenStorage)
277+
public function __construct(Security $security)
277278
{
278-
$this->tokenStorage = $tokenStorage;
279+
$this->security = $security;
279280
}
280281

281282
public function buildForm(FormBuilderInterface $builder, array $options)
@@ -286,7 +287,7 @@ and fill in the listener logic::
286287
;
287288

288289
// grab the user, do a quick sanity check that one exists
289-
$user = $this->tokenStorage->getToken()->getUser();
290+
$user = $this->security->getUser();
290291
if (!$user) {
291292
throw new \LogicException(
292293
'The FriendMessageFormType cannot be used without an authenticated user!'

profiler/matchers.rst

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -91,22 +91,22 @@ matcher::
9191
// src/AppBundle/Profiler/SuperAdminMatcher.php
9292
namespace AppBundle\Profiler;
9393

94-
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
9594
use Symfony\Component\HttpFoundation\Request;
9695
use Symfony\Component\HttpFoundation\RequestMatcherInterface;
96+
use Symfony\Component\Security\Core\Security;
9797

9898
class SuperAdminMatcher implements RequestMatcherInterface
9999
{
100-
protected $authorizationChecker;
100+
protected $security;
101101

102-
public function __construct(AuthorizationCheckerInterface $authorizationChecker)
102+
public function __construct(Security $security)
103103
{
104-
$this->authorizationChecker = $authorizationChecker;
104+
$this->security = $security;
105105
}
106106

107107
public function matches(Request $request)
108108
{
109-
return $this->authorizationChecker->isGranted('ROLE_SUPER_ADMIN');
109+
return $this->security->isGranted('ROLE_SUPER_ADMIN');
110110
}
111111
}
112112

security.rst

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -832,7 +832,7 @@ You can easily deny access from inside a controller::
832832
// The second parameter is used to specify on what object the role is tested.
833833
$this->denyAccessUnlessGranted('ROLE_ADMIN', null, 'Unable to access this page!');
834834

835-
// Old way :
835+
// Old way:
836836
// if (false === $this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) {
837837
// throw $this->createAccessDeniedException('Unable to access this page!');
838838
// }
@@ -912,9 +912,7 @@ user is logged in (you don't care about roles), then you can use
912912

913913
public function helloAction($name)
914914
{
915-
if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
916-
throw $this->createAccessDeniedException();
917-
}
915+
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
918916

919917
// ...
920918
}
@@ -1042,6 +1040,8 @@ the User object, and use the ``isGranted()`` method (or
10421040
if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
10431041
throw $this->createAccessDeniedException();
10441042
}
1043+
// equivalent shortcut:
1044+
// $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
10451045

10461046
// boo :(. Never check for the User object to see if they're logged in
10471047
if ($this->getUser()) {
@@ -1052,16 +1052,18 @@ the User object, and use the ``isGranted()`` method (or
10521052

10531053
An alternative way to get the current user in a controller is to type-hint
10541054
the controller argument with
1055-
:class:`Symfony\\Component\\Security\\Core\\User\\UserInterface`
1056-
(and default it to ``null`` if being logged-in is optional)::
1055+
:class:`Symfony\\Component\\Security\\Core\\Security`::
10571056

1058-
use Symfony\Component\Security\Core\User\UserInterface;
1057+
use Symfony\Component\Security\Core\Security;
10591058

1060-
public function indexAction(UserInterface $user = null)
1059+
public function indexAction(Security $security)
10611060
{
1062-
// $user is null when not logged-in or anon.
1061+
$user = $security->getUser();
10631062
}
10641063

1064+
.. versionadded:: 3.4
1065+
The ``Security`` utility class was introduced in Symfony 3.4.
1066+
10651067
This is only recommended for experienced developers who don't extend from the
10661068
:ref:`Symfony base controller <the-base-controller-class-services>` and
10671069
don't use the :class:`Symfony\\Bundle\\FrameworkBundle\\Controller\\ControllerTrait`

security/impersonating_user.rst

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -111,15 +111,29 @@ user rather than the impersonated user. Use the following snippet to iterate
111111
over the user's roles until you find one that a ``SwitchUserRole`` object::
112112

113113
use Symfony\Component\Security\Core\Role\SwitchUserRole;
114+
use Symfony\Component\Security\Core\Security;
115+
// ...
114116

115-
$authorizationChecker = $this->get('security.authorization_checker');
116-
$tokenStorage = $this->get('security.token_storage');
117+
public class SomeService
118+
{
119+
private $security;
120+
121+
public function __construct(Security $security)
122+
{
123+
$this->security = $security;
124+
}
125+
126+
public function someMethod()
127+
{
128+
// ...
117129

118-
if ($authorizationChecker->isGranted('ROLE_PREVIOUS_ADMIN')) {
119-
foreach ($tokenStorage->getToken()->getRoles() as $role) {
120-
if ($role instanceof SwitchUserRole) {
121-
$impersonatorUser = $role->getSource()->getUser();
122-
break;
130+
if ($this->security->isGranted('ROLE_PREVIOUS_ADMIN')) {
131+
foreach ($this->security->getToken()->getRoles() as $role) {
132+
if ($role instanceof SwitchUserRole) {
133+
$impersonatorUser = $role->getSource()->getUser();
134+
break;
135+
}
136+
}
123137
}
124138
}
125139
}

security/securing_services.rst

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -41,27 +41,27 @@ Before you add security, the class looks something like this::
4141
}
4242

4343
Your goal is to check the user's role when the ``sendNewsletter()`` method is
44-
called. The first step towards this is to inject the ``security.authorization_checker``
45-
service into the object::
44+
called. The first step towards this is to inject the ``security.helper`` service
45+
using the :class:`Symfony\\Component\\Security\\Core\\Security` class::
4646

4747
// src/AppBundle/Newsletter/NewsletterManager.php
4848

4949
// ...
50-
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
5150
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
51+
use Symfony\Component\Security\Core\Security;
5252

5353
class NewsletterManager
5454
{
55-
protected $authorizationChecker;
55+
protected $security;
5656

57-
public function __construct(AuthorizationCheckerInterface $authorizationChecker)
57+
public function __construct(Security $security)
5858
{
59-
$this->authorizationChecker = $authorizationChecker;
59+
$this->security = $security;
6060
}
6161

6262
public function sendNewsletter()
6363
{
64-
if (!$this->authorizationChecker->isGranted('ROLE_NEWSLETTER_ADMIN')) {
64+
if (!$this->security->isGranted('ROLE_NEWSLETTER_ADMIN')) {
6565
throw new AccessDeniedException();
6666
}
6767

@@ -72,8 +72,8 @@ service into the object::
7272
}
7373

7474
If you're using the :ref:`default services.yml configuration <service-container-services-load-example>`,
75-
Symfony will automatically pass the ``security.authorization_checker`` to your service
76-
thanks to autowiring and the ``AuthorizationCheckerInterface`` type-hint.
75+
Symfony will automatically pass the ``security.helper`` to your service
76+
thanks to autowiring and the ``Security`` type-hint.
7777

7878
If the current user does not have the ``ROLE_NEWSLETTER_ADMIN``, they will
7979
be prompted to log in.

session/proxy_examples.rst

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -110,15 +110,15 @@ can intercept the session before it is written::
110110

111111
use AppBundle\Entity\User;
112112
use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy;
113-
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
113+
use Symfony\Component\Security\Core\Security;
114114

115115
class ReadOnlySessionProxy extends SessionHandlerProxy
116116
{
117-
private $tokenStorage;
117+
private $security;
118118

119-
public function __construct(\SessionHandlerInterface $handler, TokenStorageInterface $tokenStorage)
119+
public function __construct(\SessionHandlerInterface $handler, Security $security)
120120
{
121-
$this->tokenStorage = $tokenStorage;
121+
$this->security = $security;
122122

123123
parent::__construct($handler);
124124
}
@@ -134,11 +134,7 @@ can intercept the session before it is written::
134134

135135
private function getUser()
136136
{
137-
if (!$token = $this->tokenStorage->getToken()) {
138-
return;
139-
}
140-
141-
$user = $token->getUser();
137+
$user = $this->security->getUser();
142138
if (is_object($user)) {
143139
return $user;
144140
}

0 commit comments

Comments
 (0)