8000 [Security] Add a Not_Full_Fledged_handler in ExceptionListener from security login by eltharin · Pull Request #57661 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Security] Add a Not_Full_Fledged_handler in ExceptionListener from security login #57661

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

Open
wants to merge 8 commits into
base: 7.4
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions src/Symfony/Bundle/SecurityBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ CHANGELOG
---

* Add `Security::isGrantedForUser()` to test user authorization without relying on the session. For example, users not currently logged in, or while processing a message from a message queue
* Add `security.firewalls.not_full_fledged_handler` option to configure behavior where user is not full fledged

7.2
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,7 @@ public function collect(Request $request, Response $response, ?\Throwable $excep
'access_denied_url' => $firewallConfig->getAccessDeniedUrl(),
'user_checker' => $firewallConfig->getUserChecker(),
'authenticators' => $firewallConfig->getAuthenticators(),
'not_full_fledged_handler' => $firewallConfig->getNotFullFledgedHandler(),
];

// generate exit impersonation path from current request
Expand Down
8000
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\Security\Http\Authorization\NotFullFledgedEqualNormalLoginHandler;
use Symfony\Component\Security\Http\Authorization\NotFullFledgedRedirectToStartAuthenticationHandler;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategy;

Expand Down Expand Up @@ -214,6 +216,17 @@ private function addFirewallsSection(ArrayNodeDefinition $rootNode, array $facto
->booleanNode('stateless')->defaultFalse()->end()
->booleanNode('lazy')->defaultFalse()->end()
->scalarNode('context')->cannotBeEmpty()->end()
->scalarNode('not_full_fledged_handler')
->defaultValue(NotFullFledgedRedirectToStartAuthenticationHandler::class)
->beforeNormalization()
->ifTrue(fn ($v): bool => 'redirect' == $v)
->then(fn ($v) => NotFullFledgedRedirectToStartAuthenticationHandler::class)
->end()
->beforeNormalization()
->ifTrue(fn ($v): bool => 'equal' == $v)
->then(fn ($v) => NotFullFledgedEqualNormalLoginHandler::class)
->end()
->end()
->arrayNode('logout')
->treatTrueLike([])
->canBeUnset()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -582,6 +582,7 @@ private function createFirewall(ContainerBuilder $container, string $id, array $

$config->replaceArgument(10, $listenerKeys);
$config->replaceArgument(11, $firewall['switch_user'] ?? null);
$config->replaceArgument(13, $firewall['not_full_fledged_handler'] ?? null);

return [$matcher, $listeners, $exceptionListener, null !== $logoutListenerId ? new Reference($logoutListenerId) : null, $firewallAuthenticationProviders];
}
Expand Down Expand Up @@ -890,6 +891,10 @@ private function createExceptionListener(ContainerBuilder $container, array $con
$listener->replaceArgument(5, $config['access_denied_url']);
}

if (isset($config['not_full_fledged_handler'])) {
$listener->replaceArgument(9, new Reference($config['not_full_fledged_handler']));
}

return $exceptionListenerId;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@
use Symfony\Component\Security\Core\User\MissingUserProvider;
use Symfony\Component\Security\Core\Validator\Constraints\UserPasswordValidator;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Http\Authorization\NotFullFledgedEqualNormalLoginHandler;
use Symfony\Component\Security\Http\Authorization\NotFullFledgedRedirectToStartAuthenticationHandler;
use Symfony\Component\Security\Http\Controller\SecurityTokenValueResolver;
use Symfony\Component\Security\Http\Controller\UserValueResolver;
use Symfony\Component\Security\Http\EventListener\IsGrantedAttributeListener;
Expand Down Expand Up @@ -230,6 +232,7 @@
[], // listeners
null, // switch_user
null, // logout
null, // not_full_fledged_handler
])

->set('security.logout_url_generator', LogoutUrlGenerator::class)
Expand Down Expand Up @@ -322,5 +325,8 @@
->set('cache.security_is_csrf_token_valid_attribute_expression_language')
->parent('cache.system')
->tag('cache.pool')

->set(NotFullFledgedRedirectToStartAuthenticationHandler::class)
->set(NotFullFledgedEqualNormalLoginHandler::class)
;
};
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@
service('security.access.denied_handler')->nullOnInvalid(),
service('logger')->nullOnInvalid(),
false, // Stateless
service('security.not.full.fledged_handler')->nullOnInvalid(),
])
->tag('monolog.logger', ['channel' => 'security'])

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,10 @@
<th>authenticators</th>
<td>{{ collector.firewall.authenticators is empty ? '(none)' : profiler_dump(collector.firewall.authenticators, maxDepth=1) }}</td>
</tr>
<tr>
<th>not_full_fledged_handler</th>
<td>{{ collector.firewall.not_full_fledged_handler ?: '(none)' }}</td>
</tr>
</tbody>
</table>
{% endif %}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public function __construct(
private readonly array $authenticators = [],
private readonly ?array $switchUser = null,
private readonly ?array $logout = null,
private readonly ?string $notFullFledgedHandler = null,
) {
}

Expand Down Expand Up @@ -104,4 +105,9 @@ public function getLogout(): ?array
{
return $this->logout;
}

public function getNotFullFledgedHandler(): ?string
{
return $this->notFullFledgedHandler;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
use Symfony\Component\Security\Http\Authentication\AuthenticatorManager;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\CsrfTokenBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\RememberMeBadge;
use Symfony\Component\Security\Http\Authorization\NotFullFledgedRedirectToStartAuthenticationHandler;

abstract class CompleteConfigurationTestCase extends TestCase
{
Expand Down Expand Up @@ -149,6 +150,7 @@ public function testFirewalls()
[],
null,
null,
null,
],
[
'secure',
Expand Down Expand Up @@ -184,6 +186,7 @@ public function testFirewalls()
'enable_csrf' => null,
'clear_site_data' => [],
],
NotFullFledgedRedirectToStartAuthenticationHandler::class,
],
[
'host',
Expand All @@ -201,6 +204,7 @@ public function testFirewalls()
],
null,
null,
NotFullFledgedRedirectToStartAuthenticationHandler::class,
],
[
'with_user_checker',
Expand All @@ -218,6 +222,7 @@ public function testFirewalls()
],
null,
null,
NotFullFledgedRedirectToStartAuthenticationHandler::class,
],
], $configs);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?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\Http\Authorization;

use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\AuthenticatedVoter;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Exception\InsufficientAuthenticationException;

/**
* NotFullFledgedHandler for considering NotFullFledged Login equal to Normal Login except if IS_AUTHENTICATED_FULLY is asked
* If IS_AUTHENTICATED_FULLY is in access denied Exception Attrribute, user is redirect to
* startAuthentication function in AuthenticationTrustResolver
* Otherwise The original AccessDeniedException is passing to accessDeniedHandler or ErrorPage or Thrown.
*
* @author Roman JOLY <eltharin18@outlook.fr>
*/
class NotFullFledgedEqualNormalLoginHandler implements NotFullFledgedHandlerInterface
{
public function handle(ExceptionEvent $event, AccessDeniedException $exception, AuthenticationTrustResolverInterface $trustResolver, ?TokenInterface $token, ?LoggerInterface $logger, callable $startAuthenticationCallback): bool
{
if (!$trustResolver->isAuthenticated($token)) {
$this->reauthenticate($startAuthenticationCallback, $event, $token, $exception, $logger);
}

foreach ($exception->getAttributes() as $attribute) {
if (\in_array($attribute, [AuthenticatedVoter::IS_AUTHENTICATED_FULLY])) {
$this->reauthenticate($startAuthenticationCallback, $event, $token, $exception, $logger);

return true;
}
}

return false;
}

private function reauthenticate(callable $startAuthenticationCallback, ExceptionEvent $event, ?TokenInterface $token, AccessDeniedException $exception, ?LoggerInterface $logger): void
{
$logger?->debug('Access denied, the user is not fully authenticated; redirecting to authentication entry point.', ['exception' => $exception]);

try {
$insufficientAuthenticationException = new InsufficientAuthenticationException('Full authentication is required to access this resource.', 0, $exception);
if (null !== $token) {
$insufficientAuthenticationException->setToken($token);
}

$event->setResponse($startAuthenticationCallback($event->getRequest(), $insufficientAuthenticationException));
} catch (\Exception $e) {
$event->setThrowable($e);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?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\Http\Authorization;

use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

/**
* This is used by the ExceptionListener to translate an AccessDeniedException
* to a Response object.
*
* @author Roman JOLY <eltharin18@outlook.fr>
*/
interface NotFullFledgedHandlerInterface
{
/**
* Allow to manage NotFullFledged cases when ExceptionListener catch AccessDeniedException
* This function can make checks and event / exception changes to change the Response
* It returns a boolean for break or not after that or continue the ExceptionListener process to decorate Exception and their response.
*
* @param $startAuthenticationCallback callable for call start function from
*
* @return bool break handleAccessDeniedException function in ExceptionListener after handle
*/
public function handle(ExceptionEvent $event, AccessDeniedException $exception, AuthenticationTrustResolverInterface $trustResolver, ?TokenInterface $token, ?LoggerInterface $logger, callable $startAuthenticationCallback): bool;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?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\Http\Authorization;

use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Exception\InsufficientAuthenticationException;

/**
* NotFullFledgedHandler for considering NotFullFledged Login has to be redirect to login page if AccessDeniedException is thrown
* When an AccessDeniedException is thrown and user is not full fledged logged, he is redirected to login page with
* start function from authenticationEntryPoint.
*
* @author Roman JOLY <eltharin18@outlook.fr>
*/
class NotFullFledgedRedirectToStartAuthenticationHandler implements NotFullFledgedHandlerInterface
{
public function handle(ExceptionEvent $event, AccessDeniedException $exception, AuthenticationTrustResolverInterface $trustResolver, ?TokenInterface $token, ?LoggerInterface $logger, callable $startAuthenticationCallback): bool
{
if (!$trustResolver->isFullFledged($token)) {
$logger?->debug('Access denied, the user is not fully authenticated; redirecting to authentication entry point.', ['exception' => $exception]);

try {
$insufficientAuthenticationException = new InsufficientAuthenticationException('Full authentication is required to access this resource.', 0, $exception);
if (null !== $token) {
$insufficientAuthenticationException->setToken($token);
}

$event->setResponse($startAuthenticationCallback($event->getRequest(), $insufficientAuthenticationException));
} catch (\Exception $e) {
$event->setThrowable($e);
}

return true;
}

return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Exception\AccountStatusException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\InsufficientAuthenticationException;
use Symfony\Component\Security\Core\Exception\LazyResponseException;
use Symfony\Component\Security\Core\Exception\LogoutException;
use Symfony\Component\Security\Http\Authorization\AccessDeniedHandlerInterface;
use Symfony\Component\Security\Http\Authorization\NotFullFledgedHandlerInterface;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
use Symfony\Component\Security\Http\EntryPoint\Exception\NotAnEntryPointException;
use Symfony\Component\Security\Http\HttpUtils;
Expand Down Expand Up @@ -57,6 +57,7 @@ public function __construct(
private ?AccessDeniedHandlerInterface $accessDeniedHandler = null,
private ?LoggerInterface $logger = null,
private bool $stateless = false,
private ?NotFullFledgedHandlerInterface $notFullFledgedHandler = null,
) {
}

Expand Down Expand Up @@ -124,22 +125,9 @@ private function handleAuthenticationException(ExceptionEvent $event, Authentica
private function handleAccessDeniedException(ExceptionEvent $event, AccessDeniedException $exception): void
{
$event->setThrowable(new AccessDeniedHttpException($exception->getMessage(), $exception));

$token = $this->tokenStorage->getToken();
if (!$this->authenticationTrustResolver->isFullFledged($token)) {
$this->logger?->debug('Access denied, the user is not fully authenticated; redirecting to authentication entry point.', ['exception' => $exception]);

try {
$insufficientAuthenticationException = new InsufficientAuthenticationException('Full authentication is required to access this resource.', 0, $exception);
if (null !== $token) {
$insufficientAuthenticationException->setToken($token);
}

$event->setResponse($this->startAuthentication($event->getRequest(), $insufficientAuthenticationException));
} catch (\Exception $e) {
$event->setThrowable($e);
}

if ($this->notFullFledgedHandler?->handle($event, $exception, $this->authenticationTrustResolver, $token, $this->logger, function ($request, $exception) {return $this->startAuthentication($request, $exception); })) {
return;
}

Expand Down
Loading
Loading
0