Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[Security][SecurityBundle] Move the Security helper to SecurityBundle #46094

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

Merged
merged 1 commit into from
Jun 5, 2022
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -186,8 +186,8 @@
use Symfony\Component\RateLimiter\Storage\CacheStorage;
use Symfony\Component\Routing\Loader\AnnotationDirectoryLoader;
use Symfony\Component\Routing\Loader\AnnotationFileLoader;
use Symfony\Component\Security\Core\AuthenticationEvents;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Semaphore\PersistingStoreInterface as SemaphoreStoreInterface;
use Symfony\Component\Semaphore\Semaphore;
Expand Down Expand Up @@ -1020,7 +1020,7 @@ private function registerWorkflowConfiguration(array $config, ContainerBuilder $
throw new LogicException('Cannot guard workflows as the ExpressionLanguage component is not installed. Try running "composer require symfony/expression-language".');
}

if (!class_exists(Security::class)) {
if (!class_exists(AuthenticationEvents::class)) {
chalasr marked this conversation as resolved.
Show resolved Hide resolved
throw new LogicException('Cannot guard workflows as the Security component is not installed. Try running "composer require symfony/security-core".');
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
use Symfony\Component\HttpKernel\Fragment\FragmentUriGeneratorInterface;
use Symfony\Component\Messenger\Transport\TransportFactory;
use Symfony\Component\PropertyAccess\PropertyAccessor;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\AuthenticationEvents;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
use Symfony\Component\Serializer\Mapping\Loader\XmlFileLoader;
use Symfony\Component\Serializer\Mapping\Loader\YamlFileLoader;
Expand Down Expand Up @@ -1036,7 +1036,7 @@ public function testTranslator()
$files,
'->registerTranslatorConfiguration() finds Form translation resources'
);
$ref = new \ReflectionClass(Security::class);
$ref = new \ReflectionClass(AuthenticationEvents::class);
chalasr marked this conversation as resolved.
Show resolved Hide resolved
$this->assertContains(
strtr(\dirname($ref->getFileName()).'/Resources/translations/security.en.xlf', '/', \DIRECTORY_SEPARATOR),
$files,
Expand Down
5 changes: 5 additions & 0 deletions 5 src/Symfony/Bundle/SecurityBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

6.2
---

* Add the `Security` helper class

6.1
---

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Symfony\Bundle\SecurityBundle\Security\FirewallContext;
use Symfony\Bundle\SecurityBundle\Security\FirewallMap;
use Symfony\Bundle\SecurityBundle\Security\LazyFirewallContext;
use Symfony\Bundle\SecurityBundle\Security\Security;
use Symfony\Component\Ldap\Security\LdapUserProvider;
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolver;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
Expand All @@ -33,7 +34,6 @@
use Symfony\Component\Security\Core\Authorization\Voter\RoleVoter;
use Symfony\Component\Security\Core\Role\RoleHierarchy;
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\ChainUserProvider;
use Symfony\Component\Security\Core\User\InMemoryUserChecker;
use Symfony\Component\Security\Core\User\InMemoryUserProvider;
Expand Down
28 changes: 28 additions & 0 deletions 28 src/Symfony/Bundle/SecurityBundle/Security/Security.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\SecurityBundle\Security;

use Psr\Container\ContainerInterface;
use Symfony\Component\Security\Core\Security as LegacySecurity;

/**
* Helper class for commonly-needed security tasks.
*
* @final
*/
class Security extends LegacySecurity
{
public function __construct(ContainerInterface $container)
{
parent::__construct($container, false);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\SecurityRequestAttributes;
use Symfony\Component\Security\Http\Util\TargetPathTrait;

class LoginFormAuthenticator extends AbstractLoginFormAuthenticator
Expand All @@ -39,7 +39,7 @@ public function authenticate(Request $request): Passport
{
$username = $request->request->get('_username', '');

$request->getSession()->set(Security::LAST_USERNAME, $username);
$request->getSession()->set(SecurityRequestAttributes::LAST_USERNAME, $username);

return new Passport(
new UserBadge($username),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
use Symfony\Component\Form\FormEvents;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\SecurityRequestAttributes;

/**
* Form type for use with the Security component's form-based authentication
Expand Down Expand Up @@ -55,18 +55,18 @@ public function buildForm(FormBuilderInterface $builder, array $options)
* session for an authentication error and last username.
*/
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($request) {
if ($request->attributes->has(Security::AUTHENTICATION_ERROR)) {
$error = $request->attributes->get(Security::AUTHENTICATION_ERROR);
if ($request->attributes->has(SecurityRequestAttributes::AUTHENTICATION_ERROR)) {
$error = $request->attributes->get(SecurityRequestAttributes::AUTHENTICATION_ERROR);
} else {
$error = $request->getSession()->get(Security::AUTHENTICATION_ERROR);
$error = $request->getSession()->get(SecurityRequestAttributes::AUTHENTICATION_ERROR);
}

if ($error) {
$event->getForm()->addError(new FormError($error->getMessage()));
}

$event->setData(array_replace((array) $event->getData(), [
'username' => $request->getSession()->get(Security::LAST_USERNAME),
'username' => $request->getSession()->get(SecurityRequestAttributes::LAST_USERNAME),
]));
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
use Psr\Container\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\SecurityRequestAttributes;
use Symfony\Contracts\Service\ServiceSubscriberInterface;
use Twig\Environment;

Expand All @@ -30,15 +30,15 @@ public function __construct(ContainerInterface $container)
public function loginAction(Request $request)
{
// get the login error if there is one
if ($request->attributes->has(Security::AUTHENTICATION_ERROR)) {
$error = $request->attributes->get(Security::AUTHENTICATION_ERROR);
if ($request->attributes->has(SecurityRequestAttributes::AUTHENTICATION_ERROR)) {
$error = $request->attributes->get(SecurityRequestAttributes::AUTHENTICATION_ERROR);
} else {
$error = $request->getSession()->get(Security::AUTHENTICATION_ERROR);
$error = $request->getSession()->get(SecurityRequestAttributes::AUTHENTICATION_ERROR);
}

return new Response($this->container->get('twig')->render('@FormLogin/Localized/login.html.twig', [
// last username entered by the user
'last_username' => $request->getSession()->get(Security::LAST_USERNAME),
'last_username' => $request->getSession()->get(SecurityRequestAttributes::LAST_USERNAME),
'error' => $error,
]));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Http\SecurityRequestAttributes;
use Symfony\Contracts\Service\ServiceSubscriberInterface;
use Twig\Environment;

Expand All @@ -32,15 +32,15 @@ public function __construct(ContainerInterface $container)
public function loginAction(Request $request, UserInterface $user = null)
{
// get the login error if there is one
if ($request->attributes->has(Security::AUTHENTICATION_ERROR)) {
$error = $request->attributes->get(Security::AUTHENTICATION_ERROR);
if ($request->attributes->has(SecurityRequestAttributes::AUTHENTICATION_ERROR)) {
$error = $request->attributes->get(SecurityRequestAttributes::AUTHENTICATION_ERROR);
} else {
$error = $request->getSession()->get(Security::AUTHENTICATION_ERROR);
$error = $request->getSession()->get(SecurityRequestAttributes::AUTHENTICATION_ERROR);
}

return new Response($this->container->get('twig')->render('@FormLogin/Login/login.html.twig', [
// last username entered by the user
'last_username' => $request->getSession()->get(Security::LAST_USERNAME),
'last_username' => $request->getSession()->get(SecurityRequestAttributes::LAST_USERNAME),
'error' => $error,
]));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\SecurityBundle\Tests\Security;

use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
use Symfony\Bundle\SecurityBundle\Security\Security;
use Symfony\Component\DependencyInjection\ServiceLocator;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\User\InMemoryUser;

class SecurityTest extends TestCase
{
public function testGetToken()
{
$token = new UsernamePasswordToken(new InMemoryUser('foo', 'bar'), 'provider');
$tokenStorage = $this->createMock(TokenStorageInterface::class);

$tokenStorage->expects($this->once())
->method('getToken')
->willReturn($token);

$container = $this->createContainer('security.token_storage', $tokenStorage);

$security = new Security($container);
$this->assertSame($token, $security->getToken());
}

/**
* @dataProvider getUserTests
*/
public function testGetUser($userInToken, $expectedUser)
{
$token = $this->createMock(TokenInterface::class);
$token->expects($this->any())
->method('getUser')
->willReturn($userInToken);
$tokenStorage = $this->createMock(TokenStorageInterface::class);

$tokenStorage->expects($this->once())
->method('getToken')
->willReturn($token);

$container = $this->createContainer('security.token_storage', $tokenStorage);

$security = new Security($container);
$this->assertSame($expectedUser, $security->getUser());
}

public function getUserTests()
{
yield [null, null];

$user = new InMemoryUser('nice_user', 'foo');
yield [$user, $user];
}

public function testIsGranted()
{
$authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class);

$authorizationChecker->expects($this->once())
->method('isGranted')
->with('SOME_ATTRIBUTE', 'SOME_SUBJECT')
->willReturn(true);

$container = $this->createContainer('security.authorization_checker', $authorizationChecker);

$security = new Security($container);
$this->assertTrue($security->isGranted('SOME_ATTRIBUTE', 'SOME_SUBJECT'));
}

private function createContainer(string $serviceId, object $serviceObject): ContainerInterface
{
return new ServiceLocator([$serviceId => fn () => $serviceObject]);
}
}
2 changes: 1 addition & 1 deletion 2 src/Symfony/Bundle/SecurityBundle/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
"symfony/password-hasher": "^5.4|^6.0",
"symfony/security-core": "^5.4|^6.0",
"symfony/security-csrf": "^5.4|^6.0",
"symfony/security-http": "^5.4|^6.0"
"symfony/security-http": "^6.2"
},
"require-dev": {
"doctrine/annotations": "^1.10.4",
Expand Down
5 changes: 5 additions & 0 deletions 5 src/Symfony/Component/Security/Core/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

6.2
---

* Deprecate the `Security` class, use `Symfony\Bundle\SecurityBundle\Security\Security` instead
chalasr marked this conversation as resolved.
Show resolved Hide resolved

6.0
---

Expand Down
32 changes: 30 additions & 2 deletions 32 src/Symfony/Component/Security/Core/Security.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,27 +12,55 @@
namespace Symfony\Component\Security\Core;

use Psr\Container\ContainerInterface;
use Symfony\Bundle\SecurityBundle\Security\Security as NewSecurityHelper;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;

/**
* Helper class for commonly-needed security tasks.
*
* @final
* @deprecated since Symfony 6.2, use \Symfony\Bundle\SecurityBundle\Security\Security instead
*/
class Security implements AuthorizationCheckerInterface
{
/**
* @deprecated since Symfony 6.2, use \Symfony\Bundle\SecurityBundle\Security\Security::ACCESS_DENIED_ERROR instead
*
* In 7.0, move this constant to the NewSecurityHelper class and make it reference SecurityRequestAttributes:ACCESS_DENIED_ERROR.
*/
public const ACCESS_DENIED_ERROR = '_security.403_error';

/**
* @deprecated since Symfony 6.2, use \Symfony\Bundle\SecurityBundle\Security\Security::AUTHENTICATION_ERROR instead
*
* In 7.0, move this constant to the NewSecurityHelper class and make it reference SecurityRequestAttributes:AUTHENTICATION_ERROR.
*/
public const AUTHENTICATION_ERROR = '_security.last_error';

/**
* @deprecated since Symfony 6.2, use \Symfony\Bundle\SecurityBundle\Security\Security::LAST_USERNAME instead
*
* In 7.0, move this constant to the NewSecurityHelper class and make it reference SecurityRequestAttributes:LAST_USERNAME.
*/
public const LAST_USERNAME = '_security.last_username';

/**
* @deprecated since Symfony 6.2, use \Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface::MAX_USERNAME_LENGTH instead
*
* In 7.0, move this constant to the NewSecurityHelper class and make it reference AuthenticatorInterface:MAX_USERNAME_LENGTH.
*/
public const MAX_USERNAME_LENGTH = 4096;

private ContainerInterface $container;

public function __construct(ContainerInterface $container)
public function __construct(ContainerInterface $container, bool $triggerDeprecation = true)
{
$this->container = $container;

if ($triggerDeprecation) {
trigger_deprecation('symfony/security-core', '6.2', 'The "%s" class is deprecated, use "%s" instead.', __CLASS__, NewSecurityHelper::class);
}
}

public function getUser(): ?UserInterface
Expand Down
3 changes: 3 additions & 0 deletions 3 src/Symfony/Component/Security/Core/Tests/SecurityTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\InMemoryUser;

/**
* @group legacy
*/
class SecurityTest extends TestCase
{
public function testGetToken()
Expand Down
Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.