Skip to content

Replacing deprecated security context #4512

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions best_practices/security.rst
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,14 @@ Authorization (i.e. Denying Access)

Symfony gives you several ways to enforce authorization, including the ``access_control``
configuration in `security.yml`_, the :ref:`@Security annotation <best-practices-security-annotation>`
and using :ref:`isGranted <best-practices-directy-isGranted>` on the ``security.context``
and using :ref:`isGranted <best-practices-directy-isGranted>` on the ``security.authorization_checker``
service directly.

.. best-practice::

* For protecting broad URL patterns, use ``access_control``;
* Whenever possible, use the ``@Security`` annotation;
* Check security directly on the ``security.context`` service whenever
* Check security directly on the ``security.authorization_checker`` service whenever
you have a more complex situation.

There are also different ways to centralize your authorization logic, like
Expand Down Expand Up @@ -313,7 +313,7 @@ Now, you can use the voter with the ``@Security`` annotation:
// ...
}

You can also use this directly with the ``security.context`` service, or
You can also use this directly with the ``security.authorization_checker`` service, or
via the even easier shortcut in a controller:

.. code-block:: php
Expand All @@ -325,7 +325,7 @@ via the even easier shortcut in a controller:
{
$post = // query for the post ...

if (!$this->get('security.context')->isGranted('edit', $post)) {
if (!$this->get('security.authorization_checker')->isGranted('edit', $post)) {
throw $this->createAccessDeniedException();
}
}
Expand Down
26 changes: 13 additions & 13 deletions book/security.rst
Original file line number Diff line number Diff line change
Expand Up @@ -438,7 +438,7 @@ Next, create the controller that will display the login form::

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\Security\Core\Security;

class SecurityController extends Controller
{
Expand All @@ -447,19 +447,19 @@ Next, create the controller that will display the login form::
$session = $request->getSession();

// get the login error if there is one
if ($request->attributes->has(SecurityContextInterface::AUTHENTICATION_ERROR)) {
if ($request->attributes->has(Security::AUTHENTICATION_ERROR)) {
$error = $request->attributes->get(
SecurityContextInterface::AUTHENTICATION_ERROR
Security::AUTHENTICATION_ERROR
);
} elseif (null !== $session && $session->has(SecurityContextInterface::AUTHENTICATION_ERROR)) {
$error = $session->get(SecurityContextInterface::AUTHENTICATION_ERROR);
$session->remove(SecurityContextInterface::AUTHENTICATION_ERROR);
} elseif (null !== $session && $session->has(Security::AUTHENTICATION_ERROR)) {
$error = $session->get(Security::AUTHENTICATION_ERROR);
$session->remove(Security::AUTHENTICATION_ERROR);
} else {
$error = '';
}

// last username entered by the user
$lastUsername = (null === $session) ? '' : $session->get(SecurityContextInterface::LAST_USERNAME);
$lastUsername = (null === $session) ? '' : $session->get(Security::LAST_USERNAME);

return $this->render(
'AcmeSecurityBundle:Security:login.html.twig',
Expand Down Expand Up @@ -1174,7 +1174,7 @@ authorization from inside a controller::

public function helloAction($name)
{
if (false === $this->get('security.context')->isGranted('ROLE_ADMIN')) {
if (false === $this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) {
throw $this->createAccessDeniedException('Unable to access this page!');
}

Expand Down Expand Up @@ -1621,12 +1621,12 @@ Retrieving the User Object
~~~~~~~~~~~~~~~~~~~~~~~~~~

After authentication, the ``User`` object of the current user can be accessed
via the ``security.context`` service. From inside a controller, this will
via the ``security.authorization_checker`` service. From inside a controller, this will
look like::

public function indexAction()
{
$user = $this->get('security.context')->getToken()->getUser();
$user = $this->get('security.authorization_checker')->getToken()->getUser();
}

In a controller this can be shortcut to:
Expand Down Expand Up @@ -1898,7 +1898,7 @@ authorization from inside a controller::

public function helloAction($name)
{
if (false === $this->get('security.context')->isGranted('ROLE_ADMIN')) {
if (false === $this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) {
throw new AccessDeniedException();
}

Expand Down Expand Up @@ -1928,7 +1928,7 @@ accepts an :class:`Symfony\\Component\\ExpressionLanguage\\Expression` object::

public function indexAction()
{
if (!$this->get('security.context')->isGranted(new Expression(
if (!$this->get('security.authorization_checker')->isGranted(new Expression(
'"ROLE_ADMIN" in roles or (user and user.isSuperAdmin())'
))) {
throw new AccessDeniedException();
Expand Down Expand Up @@ -1982,7 +1982,7 @@ Additionally, you have access to a number of functions inside the expression:
use Symfony\Component\ExpressionLanguage\Expression;
// ...

$sc = $this->get('security.context');
$sc = $this->get('security.authorization_checker');
$access1 = $sc->isGranted('IS_AUTHENTICATED_REMEMBERED');

$access2 = $sc->isGranted(new Expression(
Expand Down
8 changes: 4 additions & 4 deletions components/security/authentication.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,17 @@ an *authenticated* token if the supplied credentials were found to be valid.
The listener should then store the authenticated token in the security context::

use Symfony\Component\Security\Http\Firewall\ListenerInterface;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;

class SomeAuthenticationListener implements ListenerInterface
{
/**
* @var SecurityContextInterface
* @var TokenStorageInterface
*/
private $securityContext;
private $tokenStorage;

/**
* @var AuthenticationManagerInterface
Expand Down Expand Up @@ -54,7 +54,7 @@ The listener should then store the authenticated token in the security context::
->authenticationManager
->authenticate($unauthenticatedToken);

$this->securityContext->setToken($authenticatedToken);
$this->tokenStorage->setToken($authenticatedToken);
}
}

Expand Down
12 changes: 6 additions & 6 deletions components/security/authorization.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ Authorization
When any of the authentication providers (see :ref:`authentication_providers`)
has verified the still-unauthenticated token, an authenticated token will
be returned. The authentication listener should set this token directly
in the :class:`Symfony\\Component\\Security\\Core\\SecurityContextInterface`
using its :method:`Symfony\\Component\\Security\\Core\\SecurityContextInterface::setToken`
in the :class:`Symfony\\Component\\Security\\Core\\Authentication\\Token\\Storage\\TokenStorageInterface`
using its :method:`Symfony\\Component\\Security\\Core\\Authentication\\Token\\Storage\\TokenStorageInterface::setToken`
method.

From then on, the user is authenticated, i.e. identified. Now, other parts
Expand Down Expand Up @@ -231,15 +231,15 @@ Security Context
~~~~~~~~~~~~~~~~

The access decision manager is also available to other parts of the application
via the :method:`Symfony\\Component\\Security\\Core\\SecurityContext::isGranted`
method of the :class:`Symfony\\Component\\Security\\Core\\SecurityContext`.
via the :method:`Symfony\\Component\\Security\\Core\\Authorization\\AuthorizationChecker::isGranted`
method of the :class:`Symfony\\Component\\Security\\Core\\Authorization\\AuthorizationChecker`.
A call to this method will directly delegate the question to the access
decision manager::

use Symfony\Component\Security\SecurityContext;
use Symfony\Component\Security\Authorization\AuthorizationChecker;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

$securityContext = new SecurityContext(
$securityContext = new AuthorizationChecker(
$authenticationManager,
$accessDecisionManager
);
Expand Down
8 changes: 4 additions & 4 deletions components/security/firewall.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ The Firewall and Security Context
=================================

Central to the Security component is the security context, which is an instance
of :class:`Symfony\\Component\\Security\\Core\\SecurityContextInterface`. When all
of :class:`Symfony\\Component\\Security\\Core\\Authorization\\AuthorizationCheckerInterface`. When all
steps in the process of authenticating the user have been taken successfully,
you can ask the security context if the authenticated user has access to a
certain action or resource of the application::

use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Security\Core\Authorization\\AuthorizationChecker;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

// instance of Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface
Expand All @@ -19,14 +19,14 @@ certain action or resource of the application::
// instance of Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface
$accessDecisionManager = ...;

$securityContext = new SecurityContext(
$authorizationChecker = new AuthorizationChecker(
$authenticationManager,
$accessDecisionManager
);

// ... authenticate the user

if (!$securityContext->isGranted('ROLE_ADMIN')) {
if (!$authorizationChecker->isGranted('ROLE_ADMIN')) {
throw new AccessDeniedException();
}

Expand Down
32 changes: 16 additions & 16 deletions cookbook/form/dynamic_form_modification.rst
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ Using an event listener, your form might look like this::
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class FriendMessageFormType extends AbstractType
Expand Down Expand Up @@ -255,11 +255,11 @@ contains only this user's friends.
Luckily it is pretty easy to inject a service inside of the form. This can be
done in the constructor::

private $securityContext;
private $tokenStorage;

public function __construct(SecurityContext $securityContext)
public function __construct(TokenStorage $tokenStorage)
{
$this->securityContext = $securityContext;
$this-$tokenStorage = $tokenStorage;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

typo here

}

.. note::
Expand All @@ -275,22 +275,22 @@ done in the constructor::
Customizing the Form Type
~~~~~~~~~~~~~~~~~~~~~~~~~

Now that you have all the basics in place you can take advantage of the ``SecurityContext``
Now that you have all the basics in place you can take advantage of the ``TokenStorage``
and fill in the listener logic::

// src/Acme/DemoBundle/FormType/FriendMessageFormType.php

use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Doctrine\ORM\EntityRepository;
// ...

class FriendMessageFormType extends AbstractType
{
private $securityContext;
private $tokenStorage;

public function __construct(SecurityContext $securityContext)
public function __construct(TokenStorage $tokenStorage)
{
$this->securityContext = $securityContext;
$this->tokenStorage = $tokenStorage;
}

public function buildForm(FormBuilderInterface $builder, array $options)
Expand All @@ -301,7 +301,7 @@ and fill in the listener logic::
;

// grab the user, do a quick sanity check that one exists
$user = $this->securityContext->getToken()->getUser();
$user = $this->tokenStorage->getToken()->getUser();
if (!$user) {
throw new \LogicException(
'The FriendMessageFormType cannot be used without an authenticated user!'
Expand Down Expand Up @@ -347,7 +347,7 @@ Using the Form
Our form is now ready to use and there are two possible ways to use it inside
of a controller:

a) create it manually and remember to pass the security context to it;
a) create it manually and remember to pass the token storage to it;

or

Expand All @@ -363,9 +363,9 @@ your new form type in many places or embedding it into other forms::
{
public function newAction(Request $request)
{
$securityContext = $this->container->get('security.context');
$tokenStorage = $this->container->get('security.token_storage');
$form = $this->createForm(
new FriendMessageFormType($securityContext)
new FriendMessageFormType($tokenStorage)
);

// ...
Expand All @@ -386,7 +386,7 @@ it with :ref:`dic-tags-form-type`.
services:
acme.form.friend_message:
class: Acme\DemoBundle\Form\Type\FriendMessageFormType
arguments: ["@security.context"]
arguments: ["@security.token_storage"]
tags:
- { name: form.type, alias: acme_friend_message }

Expand All @@ -395,7 +395,7 @@ it with :ref:`dic-tags-form-type`.
<!-- app/config/config.xml -->
<services>
<service id="acme.form.friend_message" class="Acme\DemoBundle\Form\Type\FriendMessageFormType">
<argument type="service" id="security.context" />
<argument type="service" id="security.token_storage" />
<tag name="form.type" alias="acme_friend_message" />
</service>
</services>
Expand All @@ -408,7 +408,7 @@ it with :ref:`dic-tags-form-type`.
$container->setDefinition(
'acme.form.friend_message',
$definition,
array('security.context')
array('security.token_storage')
);

If you wish to create it from within a controller or any other service that has
Expand Down
16 changes: 8 additions & 8 deletions cookbook/profiler/matchers.rst
Original file line number Diff line number Diff line change
Expand Up @@ -70,22 +70,22 @@ something like::
// src/Acme/DemoBundle/Profiler/SuperAdminMatcher.php
namespace Acme\DemoBundle\Profiler;

use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestMatcherInterface;

class SuperAdminMatcher implements RequestMatcherInterface
{
protected $securityContext;
protected $authorizationChecker;

public function __construct(SecurityContext $securityContext)
public function __construct(AuthorizationCheckerInterface $authorizationChecker)
{
$this->securityContext = $securityContext;
$this->authorizationChecker = $authorizationChecker;
}

public function matches(Request $request)
{
return $this->securityContext->isGranted('ROLE_SUPER_ADMIN');
return $this->authorizationChecker->isGranted('ROLE_SUPER_ADMIN');
}
}

Expand All @@ -101,7 +101,7 @@ Then, you need to configure the service:
services:
acme_demo.profiler.matcher.super_admin:
class: "%acme_demo.profiler.matcher.super_admin.class%"
arguments: ["@security.context"]
arguments: ["@security.authorization_checker"]

.. code-block:: xml

Expand All @@ -114,7 +114,7 @@ Then, you need to configure the service:
<services>
<service id="acme_demo.profiler.matcher.super_admin"
class="%acme_demo.profiler.matcher.super_admin.class%">
<argument type="service" id="security.context" />
<argument type="service" id="security.authorization_checker" />
</services>

.. code-block:: php
Expand All @@ -129,7 +129,7 @@ Then, you need to configure the service:

$container->setDefinition('acme_demo.profiler.matcher.super_admin', new Definition(
'%acme_demo.profiler.matcher.super_admin.class%',
array(new Reference('security.context'))
array(new Reference('security.authorization_checker'))
);

Now the service is registered, the only thing left to do is configure the
Expand Down
Loading