remove deprecated role classes

This commit is contained in:
Christian Flothmann 2019-05-30 11:18:52 +02:00 committed by Robin Chalas
parent c5922d28fd
commit d64372df8c
29 changed files with 39 additions and 662 deletions

View File

@ -31,11 +31,7 @@ class TokenProcessor
{
$records['extra']['token'] = null;
if (null !== $token = $this->tokenStorage->getToken()) {
if (method_exists($token, 'getRoleNames')) {
$roles = $token->getRoleNames();
} else {
$roles = array_map(function ($role) { return $role->getRole(); }, $token->getRoles(false));
}
$roles = $token->getRoleNames();
$records['extra']['token'] = [
'username' => $token->getUsername(),

View File

@ -22,9 +22,7 @@ use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use Symfony\Component\Security\Core\Authorization\TraceableAccessDecisionManager;
use Symfony\Component\Security\Core\Authorization\Voter\TraceableVoter;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
use Symfony\Component\Security\Core\Role\SwitchUserRole;
use Symfony\Component\Security\Http\Firewall\SwitchUserListener;
use Symfony\Component\Security\Http\FirewallMapInterface;
use Symfony\Component\Security\Http\Logout\LogoutUrlGenerator;
@ -92,33 +90,15 @@ class SecurityDataCollector extends DataCollector implements LateDataCollectorIn
];
} else {
$inheritedRoles = [];
if (method_exists($token, 'getRoleNames')) {
$assignedRoles = $token->getRoleNames();
} else {
$assignedRoles = array_map(function (Role $role) { return $role->getRole(); }, $token->getRoles(false));
}
$assignedRoles = $token->getRoleNames();
$impersonatorUser = null;
if ($token instanceof SwitchUserToken) {
$impersonatorUser = $token->getOriginalToken()->getUsername();
} else {
foreach ($token->getRoles(false) as $role) {
if ($role instanceof SwitchUserRole) {
$impersonatorUser = $role->getSource()->getUsername();
break;
}
}
}
if (null !== $this->roleHierarchy) {
if (method_exists($this->roleHierarchy, 'getReachableRoleNames')) {
$allRoles = $this->roleHierarchy->getReachableRoleNames($assignedRoles);
} else {
$allRoles = array_map(function (Role $role) { return (string) $role; }, $this->roleHierarchy->getReachableRoles($token->getRoles(false)));
}
foreach ($allRoles as $role) {
foreach ($this->roleHierarchy->getReachableRoleNames($assignedRoles) as $role) {
if (!\in_array($role, $assignedRoles, true)) {
$inheritedRoles[] = $role;
}

View File

@ -28,9 +28,7 @@ use Symfony\Component\Security\Core\Authorization\AccessDecisionManager;
use Symfony\Component\Security\Core\Authorization\TraceableAccessDecisionManager;
use Symfony\Component\Security\Core\Authorization\Voter\TraceableVoter;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\Role\RoleHierarchy;
use Symfony\Component\Security\Core\Role\SwitchUserRole;
use Symfony\Component\Security\Http\FirewallMapInterface;
use Symfony\Component\Security\Http\Logout\LogoutUrlGenerator;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
@ -97,36 +95,6 @@ class SecurityDataCollectorTest extends TestCase
$this->assertSame('hhamon', $collector->getUser());
}
/**
* @group legacy
*/
public function testCollectImpersonatedToken()
{
$adminToken = new UsernamePasswordToken('yceruto', 'P4$$w0rD', 'provider', ['ROLE_ADMIN']);
$userRoles = [
'ROLE_USER',
new SwitchUserRole('ROLE_PREVIOUS_ADMIN', $adminToken),
];
$tokenStorage = new TokenStorage();
$tokenStorage->setToken(new UsernamePasswordToken('hhamon', 'P4$$w0rD', 'provider', $userRoles));
$collector = new SecurityDataCollector($tokenStorage, $this->getRoleHierarchy());
$collector->collect(new Request(), new Response());
$collector->lateCollect();
$this->assertTrue($collector->isEnabled());
$this->assertTrue($collector->isAuthenticated());
$this->assertTrue($collector->isImpersonated());
$this->assertSame('yceruto', $collector->getImpersonatorUser());
$this->assertSame('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', $collector->getTokenClass()->getValue());
$this->assertTrue($collector->supportsRoleHierarchy());
$this->assertSame(['ROLE_USER', 'ROLE_PREVIOUS_ADMIN'], $collector->getRoles()->getValue(true));
$this->assertSame([], $collector->getInheritedRoles()->getValue(true));
$this->assertSame('hhamon', $collector->getUser());
}
public function testCollectSwitchUserToken()
{
$adminToken = new UsernamePasswordToken('yceruto', 'P4$$w0rD', 'provider', ['ROLE_ADMIN']);
@ -391,22 +359,12 @@ class SecurityDataCollectorTest extends TestCase
['ROLE_USER'],
[],
],
[
[new Role('ROLE_USER', false)],
['ROLE_USER'],
[],
],
// Inherited roles
[
['ROLE_ADMIN'],
['ROLE_ADMIN'],
['ROLE_USER', 'ROLE_ALLOWED_TO_SWITCH'],
],
[
[new Role('ROLE_ADMIN', false)],
['ROLE_ADMIN'],
['ROLE_USER', 'ROLE_ALLOWED_TO_SWITCH'],
],
[
['ROLE_ADMIN', 'ROLE_OPERATOR'],
['ROLE_ADMIN', 'ROLE_OPERATOR'],

View File

@ -11,6 +11,11 @@ CHANGELOG
* `SimpleAuthenticatorInterface`, `SimpleFormAuthenticatorInterface`, `SimplePreAuthenticatorInterface`,
`SimpleAuthenticationProvider`, `SimpleAuthenticationHandler`, `SimpleFormAuthenticationListener` and
`SimplePreAuthenticationListener` have been removed. Use Guard instead.
* Removed the `Role` and `SwitchUserRole` classes. Use strings for roles instead.
* Removed the `getReachableRoles()` method from the `RoleHierarchyInterface`. Role hierarchies must implement
the `getReachableRoleNames()` method instead and return roles as strings.
* Removed the `getRoles()` method from the `TokenInterface`. Tokens must implement the `getRoleNames()` method
instead and return roles as strings.
4.3.0
-----

View File

@ -18,7 +18,6 @@ use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\AuthenticationServiceException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Role\SwitchUserRole;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
@ -89,9 +88,9 @@ abstract class UserAuthenticationProvider implements AuthenticationProviderInter
}
if ($token instanceof SwitchUserToken) {
$authenticatedToken = new SwitchUserToken($user, $token->getCredentials(), $this->providerKey, $this->getRoles($user, $token), $token->getOriginalToken());
$authenticatedToken = new SwitchUserToken($user, $token->getCredentials(), $this->providerKey, $user->getRoles(), $token->getOriginalToken());
} else {
$authenticatedToken = new UsernamePasswordToken($user, $token->getCredentials(), $this->providerKey, $this->getRoles($user, $token));
$authenticatedToken = new UsernamePasswordToken($user, $token->getCredentials(), $this->providerKey, $user->getRoles());
}
$authenticatedToken->setAttributes($token->getAttributes());
@ -107,26 +106,6 @@ abstract class UserAuthenticationProvider implements AuthenticationProviderInter
return $token instanceof UsernamePasswordToken && $this->providerKey === $token->getProviderKey();
}
/**
* Retrieves roles from user and appends SwitchUserRole if original token contained one.
*
* @return array The user roles
*/
private function getRoles(UserInterface $user, TokenInterface $token)
{
$roles = $user->getRoles();
foreach ($token->getRoles(false) as $role) {
if ($role instanceof SwitchUserRole) {
$roles[] = $role;
break;
}
}
return $roles;
}
/**
* Retrieves the user from an implementation-specific location.
*

View File

@ -11,7 +11,6 @@
namespace Symfony\Component\Security\Core\Authentication\Token;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\User\EquatableInterface;
use Symfony\Component\Security\Core\User\UserInterface;
@ -24,7 +23,6 @@ use Symfony\Component\Security\Core\User\UserInterface;
abstract class AbstractToken implements TokenInterface
{
private $user;
private $roles = [];
private $roleNames = [];
private $authenticated = false;
private $attributes = [];
@ -37,32 +35,16 @@ abstract class AbstractToken implements TokenInterface
public function __construct(array $roles = [])
{
foreach ($roles as $role) {
if (\is_string($role)) {
$role = new Role($role, false);
} elseif (!$role instanceof Role) {
throw new \InvalidArgumentException(sprintf('$roles must be an array of strings, or Role instances, but got %s.', \gettype($role)));
}
$this->roles[] = $role;
$this->roleNames[] = (string) $role;
$this->roleNames[] = $role;
}
}
public function getRoleNames(): array
{
return $this->roleNames;
}
/**
* {@inheritdoc}
*/
public function getRoles()
public function getRoleNames(): array
{
if (0 === \func_num_args() || func_get_arg(0)) {
@trigger_error(sprintf('The %s() method is deprecated since Symfony 4.3. Use the getRoleNames() method instead.', __METHOD__), E_USER_DEPRECATED);
}
return $this->roles;
return $this->roleNames;
}
/**
@ -158,7 +140,7 @@ abstract class AbstractToken implements TokenInterface
*/
public function __serialize(): array
{
return [$this->user, $this->authenticated, $this->roles, $this->attributes, $this->roleNames];
return [$this->user, $this->authenticated, null, $this->attributes, $this->roleNames];
}
/**
@ -198,15 +180,7 @@ abstract class AbstractToken implements TokenInterface
*/
public function __unserialize(array $data): void
{
[$this->user, $this->authenticated, $this->roles, $this->attributes] = $data;
// migration path to 4.3+
if (null === $this->roleNames = $data[4] ?? null) {
$this->roleNames = [];
foreach ($this->roles as $role) {
$this->roleNames[] = (string) $role;
}
}
[$this->user, $this->authenticated, , $this->attributes, $this->roleNames] = $data;
}
/**
@ -291,8 +265,8 @@ abstract class AbstractToken implements TokenInterface
$class = substr($class, strrpos($class, '\\') + 1);
$roles = [];
foreach ($this->roles as $role) {
$roles[] = $role->getRole();
foreach ($this->roleNames as $role) {
$roles[] = $role;
}
return sprintf('%s(user="%s", authenticated=%s, roles="%s")', $class, $this->getUsername(), json_encode($this->authenticated), implode(', ', $roles));

View File

@ -39,10 +39,6 @@ class TokenStorage implements TokenStorageInterface, ResetInterface
*/
public function setToken(TokenInterface $token = null)
{
if (null !== $token && !method_exists($token, 'getRoleNames')) {
@trigger_error(sprintf('Not implementing the getRoleNames() method in %s which implements %s is deprecated since Symfony 4.3.', \get_class($token), TokenInterface::class), E_USER_DEPRECATED);
}
$this->token = $token;
}

View File

@ -11,17 +11,14 @@
namespace Symfony\Component\Security\Core\Authentication\Token;
use Symfony\Component\Security\Core\Role\Role;
/**
* TokenInterface is the interface for the user authentication information.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*
* @method array __serialize() Returns all the necessary state of the object for serialization purposes - not implementing it is deprecated since Symfony 4.3
* @method void __unserialize(array $data) Restores the object state from an array given by __serialize() - not implementing it is deprecated since Symfony 4.3
* @method string[] getRoleNames() The associated roles - not implementing it is deprecated since Symfony 4.3
* @method array __serialize() Returns all the necessary state of the object for serialization purposes - not implementing it is deprecated since Symfony 4.3
* @method void __unserialize(array $data) Restores the object state from an array given by __serialize() - not implementing it is deprecated since Symfony 4.3
*/
interface TokenInterface extends \Serializable
{
@ -37,11 +34,9 @@ interface TokenInterface extends \Serializable
/**
* Returns the user roles.
*
* @return Role[] An array of Role instances
*
* @deprecated since Symfony 4.3, use the getRoleNames() method instead
* @return string[] The associated roles
*/
public function getRoles();
public function getRoleNames(): array;
/**
* Returns the user credentials.

View File

@ -18,7 +18,6 @@ use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverIn
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Authorization\ExpressionLanguage;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
/**
@ -78,22 +77,10 @@ class ExpressionVoter implements VoterInterface
private function getVariables(TokenInterface $token, $subject)
{
if (method_exists($token, 'getRoleNames')) {
$roleNames = $token->getRoleNames();
$roles = array_map(function (string $role) { return new Role($role, false); }, $roleNames);
} else {
@trigger_error(sprintf('Not implementing the getRoleNames() method in %s which implements %s is deprecated since Symfony 4.3.', \get_class($token), TokenInterface::class), E_USER_DEPRECATED);
$roleNames = $token->getRoleNames();
$roles = $token->getRoles(false);
$roleNames = array_map(function (Role $role) { return $role->getRole(); }, $roles);
}
if (null !== $this->roleHierarchy && method_exists($this->roleHierarchy, 'getReachableRoleNames')) {
if (null !== $this->roleHierarchy) {
$roleNames = $this->roleHierarchy->getReachableRoleNames($roleNames);
$roles = array_map(function (string $role) { return new Role($role, false); }, $roleNames);
} elseif (null !== $this->roleHierarchy) {
$roles = $this->roleHierarchy->getReachableRoles($roles);
$roleNames = array_map(function (Role $role) { return $role->getRole(); }, $roles);
}
$variables = [
@ -101,7 +88,6 @@ class ExpressionVoter implements VoterInterface
'user' => $token->getUser(),
'object' => $subject,
'subject' => $subject,
'roles' => $roles,
'role_names' => $roleNames,
'trust_resolver' => $this->trustResolver,
'auth_checker' => $this->authChecker,

View File

@ -12,8 +12,6 @@
namespace Symfony\Component\Security\Core\Authorization\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\Role\RoleHierarchy;
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
/**
@ -28,10 +26,6 @@ class RoleHierarchyVoter extends RoleVoter
public function __construct(RoleHierarchyInterface $roleHierarchy, string $prefix = 'ROLE_')
{
if (!method_exists($roleHierarchy, 'getReachableRoleNames')) {
@trigger_error(sprintf('Not implementing the getReachableRoleNames() method in %s which implements %s is deprecated since Symfony 4.3.', \get_class($roleHierarchy), RoleHierarchyInterface::class), E_USER_DEPRECATED);
}
$this->roleHierarchy = $roleHierarchy;
parent::__construct($prefix);
@ -42,18 +36,6 @@ class RoleHierarchyVoter extends RoleVoter
*/
protected function extractRoles(TokenInterface $token)
{
if (method_exists($this->roleHierarchy, 'getReachableRoleNames')) {
if (method_exists($token, 'getRoleNames')) {
$roles = $token->getRoleNames();
} else {
@trigger_error(sprintf('Not implementing the getRoleNames() method in %s which implements %s is deprecated since Symfony 4.3.', \get_class($token), TokenInterface::class), E_USER_DEPRECATED);
$roles = array_map(function (Role $role) { return $role->getRole(); }, $token->getRoles(false));
}
return $this->roleHierarchy->getReachableRoleNames($roles);
}
return $this->roleHierarchy->getReachableRoles($token->getRoles(false));
return $this->roleHierarchy->getReachableRoleNames($token->getRoleNames());
}
}

View File

@ -12,7 +12,6 @@
namespace Symfony\Component\Security\Core\Authorization\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Role\Role;
/**
* RoleVoter votes if any attribute starts with a given prefix.
@ -37,10 +36,6 @@ class RoleVoter implements VoterInterface
$roles = $this->extractRoles($token);
foreach ($attributes as $attribute) {
if ($attribute instanceof Role) {
$attribute = $attribute->getRole();
}
if (!\is_string($attribute) || 0 !== strpos($attribute, $this->prefix)) {
continue;
}
@ -58,12 +53,6 @@ class RoleVoter implements VoterInterface
protected function extractRoles(TokenInterface $token)
{
if (method_exists($token, 'getRoleNames')) {
return $token->getRoleNames();
}
@trigger_error(sprintf('Not implementing the getRoleNames() method in %s which implements %s is deprecated since Symfony 4.3.', \get_class($token), TokenInterface::class), E_USER_DEPRECATED);
return array_map(function (Role $role) { return $role->getRole(); }, $token->getRoles(false));
return $token->getRoleNames();
}
}

View File

@ -1,48 +0,0 @@
<?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\Component\Security\Core\Role;
/**
* Role is a simple implementation representing a role identified by a string.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since Symfony 4.3, to be removed in 5.0. Use strings as roles instead.
*/
class Role
{
private $role;
public function __construct(string $role)
{
if (\func_num_args() < 2 || func_get_arg(1)) {
@trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.3 and will be removed in 5.0. Use strings as roles instead.', __CLASS__), E_USER_DEPRECATED);
}
$this->role = $role;
}
/**
* Returns a string representation of the role.
*
* @return string
*/
public function getRole()
{
return $this->role;
}
public function __toString(): string
{
return $this->role;
}
}

View File

@ -34,31 +34,6 @@ class RoleHierarchy implements RoleHierarchyInterface
/**
* {@inheritdoc}
*/
public function getReachableRoles(array $roles)
{
if (0 === \func_num_args() || func_get_arg(0)) {
@trigger_error(sprintf('The %s() method is deprecated since Symfony 4.3 and will be removed in 5.0. Use roles as strings and the getReachableRoleNames() method instead.', __METHOD__), E_USER_DEPRECATED);
}
$reachableRoles = $roles;
foreach ($roles as $role) {
if (!isset($this->map[$role->getRole()])) {
continue;
}
foreach ($this->map[$role->getRole()] as $r) {
$reachableRoles[] = new Role($r);
}
}
return $reachableRoles;
}
/**
* @param string[] $roles
*
* @return string[]
*/
public function getReachableRoleNames(array $roles): array
{
$reachableRoles = $roles;

View File

@ -14,13 +14,14 @@ namespace Symfony\Component\Security\Core\Role;
/**
* RoleHierarchyInterface is the interface for a role hierarchy.
*
* The getReachableRoles(Role[] $roles) method that returns an array of all reachable Role objects is deprecated
* since Symfony 4.3.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @method string[] getReachableRoleNames(string[] $roles) The associated roles - not implementing it is deprecated since Symfony 4.3
*/
interface RoleHierarchyInterface
{
/**
* @param string[] $roles
*
* @return string[]
*/
public function getReachableRoleNames(array $roles): array;
}

View File

@ -1,61 +0,0 @@
<?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\Component\Security\Core\Role;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
/**
* SwitchUserRole is used when the current user temporarily impersonates
* another one.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since version 4.3, to be removed in 5.0. Use strings as roles instead.
*/
class SwitchUserRole extends Role
{
private $deprecationTriggered = false;
private $source;
/**
* @param string $role The role as a string
* @param TokenInterface $source The original token
*/
public function __construct(string $role, TokenInterface $source)
{
if ($triggerDeprecation = \func_num_args() < 3 || func_get_arg(2)) {
@trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.3 and will be removed in 5.0. Use strings as roles instead.', __CLASS__), E_USER_DEPRECATED);
$this->deprecationTriggered = true;
}
parent::__construct($role, $triggerDeprecation);
$this->source = $source;
}
/**
* Returns the original Token.
*
* @return TokenInterface The original TokenInterface instance
*/
public function getSource()
{
if (!$this->deprecationTriggered && (\func_num_args() < 1 || func_get_arg(0))) {
@trigger_error(sprintf('The "%s" class is deprecated since version 4.3 and will be removed in 5.0. Use strings as roles instead.', __CLASS__), E_USER_DEPRECATED);
$this->deprecationTriggered = true;
}
return $this->source;
}
}

View File

@ -168,7 +168,7 @@ class FakeCustomToken implements TokenInterface
{
}
public function getRoles()
public function getRoleNames(): array
{
}

View File

@ -17,7 +17,6 @@ use Symfony\Component\Security\Core\Exception\AccountExpiredException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Exception\CredentialsExpiredException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Role\SwitchUserRole;
class UserAuthenticationProviderTest extends TestCase
{
@ -180,11 +179,6 @@ class UserAuthenticationProviderTest extends TestCase
->willReturn('foo')
;
$token->expects($this->once())
->method('getRoles')
->willReturn([])
;
$authToken = $provider->authenticate($token);
$this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', $authToken);
@ -194,45 +188,6 @@ class UserAuthenticationProviderTest extends TestCase
$this->assertEquals(['foo' => 'bar'], $authToken->getAttributes(), '->authenticate() copies token attributes');
}
/**
* @group legacy
*/
public function testAuthenticateWithPreservingRoleSwitchUserRole()
{
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user->expects($this->once())
->method('getRoles')
->willReturn(['ROLE_FOO'])
;
$provider = $this->getProvider();
$provider->expects($this->once())
->method('retrieveUser')
->willReturn($user)
;
$token = $this->getSupportedToken();
$token->expects($this->once())
->method('getCredentials')
->willReturn('foo')
;
$switchUserRole = new SwitchUserRole('foo', $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
$token->expects($this->once())
->method('getRoles')
->willReturn([$switchUserRole])
;
$authToken = $provider->authenticate($token);
$this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', $authToken);
$this->assertSame($user, $authToken->getUser());
$this->assertContains('ROLE_FOO', $authToken->getRoleNames(), '', false, false);
$this->assertContains($switchUserRole, $authToken->getRoles(), '', false, false);
$this->assertEquals('foo', $authToken->getCredentials());
$this->assertEquals(['foo' => 'bar'], $authToken->getAttributes(), '->authenticate() copies token attributes');
}
public function testAuthenticatePreservesOriginalToken()
{
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();

View File

@ -13,8 +13,6 @@ namespace Symfony\Component\Security\Core\Tests\Authentication\Token;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\Token\AbstractToken;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\UserInterface;
class AbstractTokenTest extends TestCase
@ -47,7 +45,7 @@ class AbstractTokenTest extends TestCase
public function testSerialize()
{
$token = new ConcreteToken(['ROLE_FOO', new Role('ROLE_BAR', false)]);
$token = new ConcreteToken(['ROLE_FOO', 'ROLE_BAR']);
$token->setAttributes(['foo' => 'bar']);
$uToken = unserialize(serialize($token));
@ -56,55 +54,12 @@ class AbstractTokenTest extends TestCase
$this->assertEquals($token->getAttributes(), $uToken->getAttributes());
}
/**
* @group legacy
*/
public function testSerializeWithRoleObjects()
{
$user = new User('name', 'password', [new Role('ROLE_FOO'), new Role('ROLE_BAR')]);
$token = new ConcreteToken($user->getRoles(), $user);
$serialized = serialize($token);
$unserialized = unserialize($serialized);
$roles = $unserialized->getRoles();
$this->assertEquals($roles, $user->getRoles());
}
public function testConstructor()
{
$token = new ConcreteToken(['ROLE_FOO']);
$this->assertEquals(['ROLE_FOO'], $token->getRoleNames());
}
/**
* @group legacy
*/
public function testConstructorWithRoleObjects()
{
$token = new ConcreteToken([new Role('ROLE_FOO')]);
$this->assertEquals(['ROLE_FOO'], $token->getRoleNames());
$token = new ConcreteToken([new Role('ROLE_FOO'), 'ROLE_BAR']);
$this->assertEquals(['ROLE_FOO', 'ROLE_BAR'], $token->getRoleNames());
}
/**
* @group legacy
*/
public function testGetRoles()
{
$token = new ConcreteToken(['ROLE_FOO']);
$this->assertEquals([new Role('ROLE_FOO')], $token->getRoles());
$token = new ConcreteToken([new Role('ROLE_FOO')]);
$this->assertEquals([new Role('ROLE_FOO')], $token->getRoles());
$token = new ConcreteToken([new Role('ROLE_FOO'), 'ROLE_BAR']);
$this->assertEquals([new Role('ROLE_FOO'), new Role('ROLE_BAR')], $token->getRoles());
}
public function testAuthenticatedFlag()
{
$token = new ConcreteToken();

View File

@ -16,21 +16,9 @@ use Symfony\Component\Security\Core\Authentication\Token\AbstractToken;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\ExpressionVoter;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Role\Role;
class ExpressionVoterTest extends TestCase
{
/**
* @group legacy
* @dataProvider getVoteTests
*/
public function testVote($roles, $attributes, $expected, $tokenExpectsGetRoles = true, $expressionLanguageExpectsEvaluate = true)
{
$voter = new ExpressionVoter($this->createExpressionLanguage($expressionLanguageExpectsEvaluate), $this->createTrustResolver(), $this->createAuthorizationChecker());
$this->assertSame($expected, $voter->vote($this->getToken($roles, $tokenExpectsGetRoles), null, $attributes));
}
/**
* @dataProvider getVoteTests
*/
@ -54,22 +42,6 @@ class ExpressionVoterTest extends TestCase
];
}
protected function getToken(array $roles, $tokenExpectsGetRoles = true)
{
foreach ($roles as $i => $role) {
$roles[$i] = new Role($role);
}
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
if ($tokenExpectsGetRoles) {
$token->expects($this->once())
->method('getRoles')
->willReturn($roles);
}
return $token;
}
protected function getTokenWithRoleNames(array $roles, $tokenExpectsGetRoles = true)
{
$token = $this->getMockBuilder(AbstractToken::class)->getMock();

View File

@ -17,17 +17,6 @@ use Symfony\Component\Security\Core\Role\RoleHierarchy;
class RoleHierarchyVoterTest extends RoleVoterTest
{
/**
* @group legacy
* @dataProvider getVoteTests
*/
public function testVote($roles, $attributes, $expected)
{
$voter = new RoleHierarchyVoter(new RoleHierarchy(['ROLE_FOO' => ['ROLE_FOOBAR']]));
$this->assertSame($expected, $voter->vote($this->getToken($roles), null, $attributes));
}
/**
* @dataProvider getVoteTests
*/
@ -45,28 +34,6 @@ class RoleHierarchyVoterTest extends RoleVoterTest
]);
}
/**
* @group legacy
* @dataProvider getLegacyVoteOnRoleObjectsTests
*/
public function testVoteOnRoleObjects($roles, $attributes, $expected)
{
$voter = new RoleHierarchyVoter(new RoleHierarchy(['ROLE_FOO' => ['ROLE_FOOBAR']]));
$this->assertSame($expected, $voter->vote($this->getToken($roles), null, $attributes));
}
/**
* @group legacy
* @dataProvider getVoteWithEmptyHierarchyTests
*/
public function testVoteWithEmptyHierarchy($roles, $attributes, $expected)
{
$voter = new RoleHierarchyVoter(new RoleHierarchy([]));
$this->assertSame($expected, $voter->vote($this->getToken($roles), null, $attributes));
}
/**
* @dataProvider getVoteWithEmptyHierarchyTests
*/

View File

@ -15,21 +15,9 @@ use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\Token\AbstractToken;
use Symfony\Component\Security\Core\Authorization\Voter\RoleVoter;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Role\Role;
class RoleVoterTest extends TestCase
{
/**
* @group legacy
* @dataProvider getVoteTests
*/
public function testVote($roles, $attributes, $expected)
{
$voter = new RoleVoter();
$this->assertSame($expected, $voter->vote($this->getToken($roles), null, $attributes));
}
/**
* @dataProvider getVoteTests
*/
@ -56,38 +44,6 @@ class RoleVoterTest extends TestCase
];
}
/**
* @group legacy
* @dataProvider getLegacyVoteOnRoleObjectsTests
*/
public function testVoteOnRoleObjects($roles, $attributes, $expected)
{
$voter = new RoleVoter();
$this->assertSame($expected, $voter->vote($this->getToken($roles), null, $attributes));
}
public function getLegacyVoteOnRoleObjectsTests()
{
return [
[['ROLE_BAR'], [new Role('ROLE_BAR')], VoterInterface::ACCESS_GRANTED],
[['ROLE_BAR'], [new Role('ROLE_FOO')], VoterInterface::ACCESS_DENIED],
];
}
protected function getToken(array $roles)
{
foreach ($roles as $i => $role) {
$roles[$i] = new Role($role);
}
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$token->expects($this->once())
->method('getRoles')
->willReturn($roles);
return $token;
}
protected function getTokenWithRoleNames(array $roles)
{
$token = $this->getMockBuilder(AbstractToken::class)->getMock();

View File

@ -12,28 +12,10 @@
namespace Symfony\Component\Security\Core\Tests\Role;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\Role\RoleHierarchy;
class RoleHierarchyTest extends TestCase
{
/**
* @group legacy
*/
public function testGetReachableRoles()
{
$role = new RoleHierarchy([
'ROLE_ADMIN' => ['ROLE_USER'],
'ROLE_SUPER_ADMIN' => ['ROLE_ADMIN', 'ROLE_FOO'],
]);
$this->assertEquals([new Role('ROLE_USER')], $role->getReachableRoles([new Role('ROLE_USER')]));
$this->assertEquals([new Role('ROLE_FOO')], $role->getReachableRoles([new Role('ROLE_FOO')]));
$this->assertEquals([new Role('ROLE_ADMIN'), new Role('ROLE_USER')], $role->getReachableRoles([new Role('ROLE_ADMIN')]));
$this->assertEquals([new Role('ROLE_FOO'), new Role('ROLE_ADMIN'), new Role('ROLE_USER')], $role->getReachableRoles([new Role('ROLE_FOO'), new Role('ROLE_ADMIN')]));
$this->assertEquals([new Role('ROLE_SUPER_ADMIN'), new Role('ROLE_ADMIN'), new Role('ROLE_FOO'), new Role('ROLE_USER')], $role->getReachableRoles([new Role('ROLE_SUPER_ADMIN')]));
}
public function testGetReachableRoleNames()
{
$role = new RoleHierarchy([

View File

@ -1,28 +0,0 @@
<?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\Component\Security\Core\Tests\Role;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Role\Role;
/**
* @group legacy
*/
class RoleTest extends TestCase
{
public function testGetRole()
{
$role = new Role('FOO');
$this->assertEquals('FOO', $role->getRole());
}
}

View File

@ -1,35 +0,0 @@
<?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\Component\Security\Core\Tests\Role;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Role\SwitchUserRole;
/**
* @group legacy
*/
class SwitchUserRoleTest extends TestCase
{
public function testGetSource()
{
$role = new SwitchUserRole('FOO', $token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
$this->assertSame($token, $role->getSource());
}
public function testGetRole()
{
$role = new SwitchUserRole('FOO', $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
$this->assertEquals('FOO', $role->getRole());
}
}

View File

@ -11,8 +11,6 @@
namespace Symfony\Component\Security\Core\User;
use Symfony\Component\Security\Core\Role\Role;
/**
* Represents the interface that all user classes must implement.
*
@ -44,7 +42,7 @@ interface UserInterface
* and populated in any number of different ways when the user object
* is created.
*
* @return (Role|string)[] The user roles
* @return string[] The user roles
*/
public function getRoles();

View File

@ -25,7 +25,6 @@ use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Role\SwitchUserRole;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Http\Event\DeauthenticatedEvent;
@ -197,13 +196,6 @@ class ContextListener implements ListenerInterface
if ($token instanceof SwitchUserToken) {
$context['impersonator_username'] = $token->getOriginalToken()->getUsername();
} else {
foreach ($token->getRoles(false) as $role) {
if ($role instanceof SwitchUserRole) {
$context['impersonator_username'] = $role->getSource(false)->getUsername();
break;
}
}
}
$this->logger->debug('User was reloaded from a user provider.', $context);

View File

@ -23,7 +23,6 @@ use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Role\SwitchUserRole;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
@ -151,7 +150,6 @@ class SwitchUserListener implements ListenerInterface
$this->userChecker->checkPostAuth($user);
$roles = $user->getRoles();
$roles[] = new SwitchUserRole('ROLE_PREVIOUS_ADMIN', $this->tokenStorage->getToken(), false);
$token = new SwitchUserToken($user, $user->getPassword(), $this->providerKey, $roles, $token);
@ -194,12 +192,6 @@ class SwitchUserListener implements ListenerInterface
return $token->getOriginalToken();
}
foreach ($token->getRoles(false) as $role) {
if ($role instanceof SwitchUserRole) {
return $role->getSource();
}
}
return null;
}
}

View File

@ -18,7 +18,6 @@ use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Role\SwitchUserRole;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Http\Event\SwitchUserEvent;
use Symfony\Component\Security\Http\Firewall\SwitchUserListener;
@ -95,7 +94,7 @@ class SwitchUserListenerTest extends TestCase
public function testExitUserUpdatesToken()
{
$originalToken = new UsernamePasswordToken('username', '', 'key', []);
$this->tokenStorage->setToken(new SwitchUserToken('username', '', 'key', [new SwitchUserRole('ROLE_PREVIOUS', $originalToken, false)], $originalToken));
$this->tokenStorage->setToken(new SwitchUserToken('username', '', 'key', ['ROLE_USER'], $originalToken));
$this->request->query->set('_switch_user', SwitchUserListener::EXIT_VALUE);
@ -109,22 +108,6 @@ class SwitchUserListenerTest extends TestCase
$this->assertSame($originalToken, $this->tokenStorage->getToken());
}
/**
* @group legacy
*/
public function testExitUserBasedOnSwitchUserRoleUpdatesToken()
{
$originalToken = new UsernamePasswordToken('username', '', 'key', []);
$this->tokenStorage->setToken(new UsernamePasswordToken('username', '', 'key', [new SwitchUserRole('ROLE_PREVIOUS', $originalToken, false)], $originalToken));
$this->request->query->set('_switch_user', SwitchUserListener::EXIT_VALUE);
$listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
$listener($this->event);
$this->assertSame($originalToken, $this->tokenStorage->getToken());
}
public function testExitUserDispatchesEventWithRefreshedUser()
{
$originalUser = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
@ -136,7 +119,7 @@ class SwitchUserListenerTest extends TestCase
->with($originalUser)
->willReturn($refreshedUser);
$originalToken = new UsernamePasswordToken($originalUser, '', 'key');
$this->tokenStorage->setToken(new SwitchUserToken('username', '', 'key', [new SwitchUserRole('ROLE_PREVIOUS', $originalToken, false)], $originalToken));
$this->tokenStorage->setToken(new SwitchUserToken('username', '', 'key', ['ROLE_USER'], $originalToken));
$this->request->query->set('_switch_user', SwitchUserListener::EXIT_VALUE);
$dispatcher = $this->getMockBuilder(EventDispatcherInterface::class)->getMock();
@ -163,7 +146,7 @@ class SwitchUserListenerTest extends TestCase
->expects($this->never())
->method('refreshUser');
$originalToken = new UsernamePasswordToken($originalUser, '', 'key');
$this->tokenStorage->setToken(new SwitchUserToken('username', '', 'key', [new SwitchUserRole('ROLE_PREVIOUS', $originalToken, false)], $originalToken));
$this->tokenStorage->setToken(new SwitchUserToken('username', '', 'key', ['ROLE_USER'], $originalToken));
$this->request->query->set('_switch_user', SwitchUserListener::EXIT_VALUE);
$dispatcher = $this->getMockBuilder(EventDispatcherInterface::class)->getMock();

View File

@ -13,9 +13,7 @@ namespace Symfony\Component\Workflow\EventListener;
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Component\Workflow\Event\GuardEvent;
@ -37,10 +35,6 @@ class GuardListener
public function __construct(array $configuration, ExpressionLanguage $expressionLanguage, TokenStorageInterface $tokenStorage, AuthorizationCheckerInterface $authorizationChecker, AuthenticationTrustResolverInterface $trustResolver, RoleHierarchyInterface $roleHierarchy = null, ValidatorInterface $validator = null)
{
if (null !== $roleHierarchy && !method_exists($roleHierarchy, 'getReachableRoleNames')) {
@trigger_error(sprintf('Not implementing the getReachableRoleNames() method in %s which implements %s is deprecated since Symfony 4.3.', \get_class($roleHierarchy), RoleHierarchyInterface::class), E_USER_DEPRECATED);
}
$this->configuration = $configuration;
$this->expressionLanguage = $expressionLanguage;
$this->tokenStorage = $tokenStorage;
@ -86,29 +80,16 @@ class GuardListener
throw new InvalidTokenConfigurationException(sprintf('There are no tokens available for workflow %s.', $event->getWorkflowName()));
}
if (method_exists($token, 'getRoleNames')) {
$roleNames = $token->getRoleNames();
$roles = array_map(function (string $role) { return new Role($role, false); }, $roleNames);
} else {
@trigger_error(sprintf('Not implementing the getRoleNames() method in %s which implements %s is deprecated since Symfony 4.3.', \get_class($token), TokenInterface::class), E_USER_DEPRECATED);
$roleNames = $token->getRoleNames();
$roles = $token->getRoles(false);
$roleNames = array_map(function (Role $role) { return $role->getRole(); }, $roles);
}
if (null !== $this->roleHierarchy && method_exists($this->roleHierarchy, 'getReachableRoleNames')) {
if (null !== $this->roleHierarchy) {
$roleNames = $this->roleHierarchy->getReachableRoleNames($roleNames);
$roles = array_map(function (string $role) { return new Role($role, false); }, $roleNames);
} elseif (null !== $this->roleHierarchy) {
$roles = $this->roleHierarchy->getReachableRoles($roles);
$roleNames = array_map(function (Role $role) { return $role->getRole(); }, $roles);
}
$variables = [
'token' => $token,
'user' => $token->getUser(),
'subject' => $event->getSubject(),
'roles' => $roles,
'role_names' => $roleNames,
// needed for the is_granted expression function
'auth_checker' => $this->authorizationChecker,