Skip to content

[Security] Use NullToken while checking authorization #37620

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
Jul 31, 2020
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
6 changes: 6 additions & 0 deletions UPGRADE-5.2.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,9 @@ Validator
* })
*/
```

Security
--------

* [BC break] In the experimental authenticator-based system, * `TokenInterface::getUser()`
returns `null` in case of unauthenticated session.
3 changes: 2 additions & 1 deletion src/Symfony/Component/Security/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ CHANGELOG
5.2.0
-----

* Added attributes on ``Passport``
* Added attributes on `Passport`
* Changed `AuthorizationChecker` to call the access decision manager in unauthenticated sessions with a `NullToken`

5.1.0
-----
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\Security\Core\Authentication;

use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Authentication\Token\NullToken;
use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;

Expand All @@ -31,7 +32,7 @@ public function isAnonymous(TokenInterface $token = null)
return false;
}

return $token instanceof AnonymousToken;
return $token instanceof AnonymousToken || $token instanceof NullToken;
}

/**
Expand Down
105 changes: 105 additions & 0 deletions src/Symfony/Component/Security/Core/Authentication/Token/NullToken.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
<?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\Authentication\Token;

/**
* @author Wouter de Jong <wouter@wouterj.nl>
*/
class NullToken implements TokenInterface
{
public function __toString(): string
{
return '';
}

public function getRoleNames(): array
{
return [];
}

public function getCredentials()
{
return '';
}

public function getUser()
{
return null;
}

public function setUser($user)
{
throw new \BadMethodCallException('Cannot set user on a NullToken.');
}

public function getUsername()
{
return '';
}

public function isAuthenticated()
{
return true;
}

public function setAuthenticated(bool $isAuthenticated)
{
throw new \BadMethodCallException('Cannot change authentication state of NullToken.');
}

public function eraseCredentials()
{
}

public function getAttributes()
{
return [];
}

public function setAttributes(array $attributes)
{
throw new \BadMethodCallException('Cannot set attributes of NullToken.');
}

public function hasAttribute(string $name)
{
return false;
}

public function getAttribute(string $name)
{
return null;
}

public function setAttribute(string $name, $value)
{
throw new \BadMethodCallException('Cannot add attribute to NullToken.');
}

public function __serialize(): array
{
return [];
}

public function __unserialize(array $data): void
{
}

public function serialize()
{
return '';
}

public function unserialize($serialized)
{
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\Security\Core\Authorization;

use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\NullToken;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;

Expand Down Expand Up @@ -52,11 +53,11 @@ final public function isGranted($attribute, $subject = null): bool
throw new AuthenticationCredentialsNotFoundException('The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL.');
}

return false;
}

if ($this->alwaysAuthenticate || !$token->isAuthenticated()) {
$this->tokenStorage->setToken($token = $this->authenticationManager->authenticate($token));
$token = new NullToken();
} else {
if ($this->alwaysAuthenticate || !$token->isAuthenticated()) {
$this->tokenStorage->setToken($token = $this->authenticationManager->authenticate($token));
}
}

return $this->accessDecisionManager->decide($token, [$attribute], $subject);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\Security\Core\Tests\Authorization;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\Token\NullToken;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;
Expand Down Expand Up @@ -77,7 +78,13 @@ public function testVoteWithoutAuthenticationTokenAndExceptionOnNoTokenIsFalse()
{
$authorizationChecker = new AuthorizationChecker($this->tokenStorage, $this->authenticationManager, $this->accessDecisionManager, false, false);

$this->assertFalse($authorizationChecker->isGranted('ROLE_FOO'));
$this->accessDecisionManager
->expects($this->once())
->method('decide')
->with($this->isInstanceOf(NullToken::class))
->willReturn(true);

$this->assertTrue($authorizationChecker->isGranted('ANONYMOUS'));
}

/**
Expand Down
15 changes: 2 additions & 13 deletions src/Symfony/Component/Security/Http/Firewall/AccessListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\NullToken;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\AuthenticatedVoter;
Expand Down Expand Up @@ -89,19 +90,7 @@ public function authenticate(RequestEvent $event)
throw new AuthenticationCredentialsNotFoundException('A Token was not found in the TokenStorage.');
}

if ([AuthenticatedVoter::IS_AUTHENTICATED_ANONYMOUSLY] === $attributes) {
trigger_deprecation('symfony/security-http', '5.1', 'Using "IS_AUTHENTICATED_ANONYMOUSLY" in your access_control rules when using the authenticator Security system is deprecated, use "PUBLIC_ACCESS" instead.');

return;
}

if ([self::PUBLIC_ACCESS] !== $attributes) {
throw $this->createAccessDeniedException($request, $attributes);
}
}

if ([self::PUBLIC_ACCESS] === $attributes) {
return;
$token = new NullToken();
}

if (!$token->isAuthenticated()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\NullToken;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
Expand Down Expand Up @@ -245,9 +246,15 @@ public function testHandleWhenTheSecurityTokenStorageHasNoTokenAndExceptionOnTok
->willReturn([['foo' => 'bar'], null])
;

$accessDecisionManager = $this->createMock(AccessDecisionManagerInterface::class);
$accessDecisionManager->expects($this->once())
->method('decide')
->with($this->isInstanceOf(NullToken::class))
->willReturn(false);

$listener = new AccessListener(
$tokenStorage,
$this->getMockBuilder('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface')->getMock(),
$accessDecisionManager,
$accessMap,
$this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock(),
false
Expand All @@ -268,17 +275,21 @@ public function testHandleWhenPublicAccessIsAllowedAndExceptionOnTokenIsFalse()
->willReturn([[AccessListener::PUBLIC_ACCESS], null])
;

$accessDecisionManager = $this->createMock(AccessDecisionManagerInterface::class);
$accessDecisionManager->expects($this->once())
->method('decide')
->with($this->isInstanceOf(NullToken::class), [AccessListener::PUBLIC_ACCESS])
->willReturn(true);

$listener = new AccessListener(
$tokenStorage,
$this->getMockBuilder('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface')->getMock(),
$accessDecisionManager,
$accessMap,
$this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock(),
false
);

$listener(new RequestEvent($this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MASTER_REQUEST));

$this->expectNotToPerformAssertions();
}

public function testHandleWhenPublicAccessWhileAuthenticated()
Expand All @@ -295,17 +306,21 @@ public function testHandleWhenPublicAccessWhileAuthenticated()
->willReturn([[AccessListener::PUBLIC_ACCESS], null])
;

$accessDecisionManager = $this->createMock(AccessDecisionManagerInterface::class);
$accessDecisionManager->expects($this->once())
->method('decide')
->with($this->equalTo($token), [AccessListener::PUBLIC_ACCESS])
->willReturn(true);

$listener = new AccessListener(
$tokenStorage,
$this->getMockBuilder('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface')->getMock(),
$accessDecisionManager,
$accessMap,
$this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock(),
false
);

$listener(new RequestEvent($this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MASTER_REQUEST));

$this->expectNotToPerformAssertions();
}

public function testHandleMWithultipleAttributesShouldBeHandledAsAnd()
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/Security/Http/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"require": {
"php": ">=7.2.5",
"symfony/deprecation-contracts": "^2.1",
"symfony/security-core": "^5.1",
"symfony/security-core": "^5.2",
"symfony/http-foundation": "^4.4.7|^5.0.7",
"symfony/http-kernel": "^4.4|^5.0",
"symfony/polyfill-php80": "^1.15",
Expand Down