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 1 commit
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
Prev Previous commit
Next Next commit
change follow review
  • Loading branch information
eltharin committed Jan 9, 2025
commit d170f59368b8ffe8b31e43c56234a47890ed4fa6
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategy;
use Symfony\Component\Security\Http\Authorization\SameAsNotFullFledgedHandler;
use Symfony\Component\Security\Http\Authorization\NotFullFledgedEqualNormalLoginHandler;
use Symfony\Component\Security\Http\Authorization\NotFullFledgedRedirectToStartAuthenticationHandler;

/**
* SecurityExtension configuration structure.
Expand Down Expand Up @@ -216,13 +217,16 @@ private function addFirewallsSection(ArrayNodeDefinition $rootNode, array $facto
->booleanNode('lazy')->defaultFalse()->end()
->scalarNode('context')->cannotBeEmpty()->end()
->scalarNode('not_full_fledged_handler')
->defaultValue(NotFullFledgedRedirectToStartAuthenticationHandler::class)
->beforeNormalization()
->ifTrue(fn ($v): bool => $v == 'original')
->then(fn ($v) => null)
->ifTrue(fn ($v): bool => $v == 'same')
->then(fn ($v) => SameAsNotFullFledgedHandler::class)
->end()
->ifTrue(fn ($v): bool => $v == 'redirect')
->then(fn ($v) => NotFullFledgedRedirectToStartAuthenticationHandler::class)
->end()
->beforeNormalization()
->ifTrue(fn ($v): bool => $v == 'equal')
->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 @@ -45,7 +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\SameAsNotFullFledgedHandler;
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 @@ -325,6 +326,7 @@
->parent('cache.system')
->tag('cache.pool')

->set('security.same_as_not_full_fledged_handle', SameAsNotFullFledgedHandler::class)
->set(NotFullFledgedRedirectToStartAuthenticationHandler::class)
->set(NotFullFledgedEqualNormalLoginHandler::class)
;
};
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 @@ -185,7 +186,7 @@ public function testFirewalls()
'enable_csrf' => null,
'clear_site_data' => [],
],
null,
NotFullFledgedRedirectToStartAuthenticationHandler::class,
],
[
'host',
Expand All @@ -203,7 +204,7 @@ public function testFirewalls()
],
null,
null,
null,
NotFullFledgedRedirectToStartAuthenticationHandler::class,
],
[
'with_user_checker',
Expand All @@ -221,7 +222,7 @@ public function testFirewalls()
],
null,
null,
null,
NotFullFledgedRedirectToStartAuthenticationHandler::class,
],
], $configs);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?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\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
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;< 8000 /span>
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 $starAuthenticationCallback): bool
{
if( !$trustResolver->isAuthenticated($token)) {
$this->reauthenticate($starAuthenticationCallback, $event, $token, $exception, $logger);
}

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

return false;
}

private function reauthenticate(callable $starAuthenticationCallback, 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($starAuthenticationCallback($event->getRequest(), $insufficientAuthenticationException));
} catch (\Exception $e) {
$event->setThrowable($e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@

namespace Symfony\Component\Security\Http\Authorization;

use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
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;
Expand All @@ -26,10 +28,11 @@
interface NotFullFledgedHandlerInterface
{
/**
* Handles a not full fledged case for acces denied failure.
* @return null|Response
* null: throw original AcessDeniedException
* Response: you can return your own response, AccesDeniedException wil be ignored
* Allow to manage NotFullFledged cases when ExceptionListener catch AccessDeniedException
*
* @param $starAuthenticationCallback callable for call start function from
*
* @return boolean break handleAccessDeniedException function in ExceptionListener after handle
*/
public function handle(Request $request, AccessDeniedException $accessDeniedException, AuthenticationTrustResolverInterface $trustResolver, ?TokenInterface $token, callable $reauthenticateResponse): ?Response;
public function handle( ExceptionEvent $event, AccessDeniedException $exception, AuthenticationTrustResolverInterface $trustResolver, ?TokenInterface $token, ?LoggerInterface $logger, callable $starAuthenticationCallback): bool;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?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\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
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 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 $starAuthenticationCallback): 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($starAuthenticationCallback($event->getRequest(), $insufficientAuthenticationException));
} catch (\Exception $e) {
$event->setThrowable($e);
}

return true;
}

return false;
}
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
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;
Expand Down Expand Up @@ -126,36 +125,11 @@ 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)) {

$starAuthenticationResponse = function () use($exception, $event, $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(null === $this->notFullFledgedHandler) {
$starAuthenticationResponse();
return;
}

$response = $this->notFullFledgedHandler->handle($event->getRequest(), $exception,$this->authenticationTrustResolver, $token, $starAuthenticationResponse);

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

$this->logger?->debug('Access denied, the user is neither anonymous, nor remember-me.', ['exception' => $exception]);
Expand Down
Loading
0