Skip to content
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 @@ -26,6 +26,7 @@
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\PasswordUpgradeBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\RememberMeBadge;
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;
Expand Down Expand Up @@ -80,15 +81,20 @@ public function supports(Request $request): ?bool
public function authenticate(Request $request): Passport
{
try {
$credentials = $this->getCredentials($request);
$data = json_decode($request->getContent());
if (!$data instanceof \stdClass) {
throw new BadRequestHttpException('Invalid JSON.');
}

$credentials = $this->getCredentials($data);
} catch (BadRequestHttpException $e) {
$request->setRequestFormat('json');

throw $e;
}

$userBadge = new UserBadge($credentials['username'], $this->userProvider->loadUserByIdentifier(...));
$passport = new Passport($userBadge, new PasswordCredentials($credentials['password']));
$passport = new Passport($userBadge, new PasswordCredentials($credentials['password']), [new RememberMeBadge((array) $data)]);

if ($this->userProvider instanceof PasswordUpgraderInterface) {
$passport->addBadge(new PasswordUpgradeBadge($credentials['password'], $this->userProvider));
Expand Down Expand Up @@ -136,13 +142,8 @@ public function setTranslator(TranslatorInterface $translator)
$this->translator = $translator;
}

private function getCredentials(Request $request): array
private function getCredentials(\stdClass $data): array
{
$data = json_decode($request->getContent());
if (!$data instanceof \stdClass) {
throw new BadRequestHttpException('Invalid JSON.');
}

$credentials = [];
try {
$credentials['username'] = $this->propertyAccessor->getValue($data, $this->options['username_path']);
Expand All @@ -156,6 +157,7 @@ private function getCredentials(Request $request): array

try {
$credentials['password'] = $this->propertyAccessor->getValue($data, $this->options['password_path']);
$this->propertyAccessor->setValue($data, $this->options['password_path'], null);

if (!\is_string($credentials['password'])) {
throw new BadRequestHttpException(sprintf('The key "%s" must be a string.', $this->options['password_path']));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ class RememberMeBadge implements BadgeInterface
{
private bool $enabled = false;

public function __construct(
public readonly array $parameters = [],
) {
}

/**
* Enables remember-me cookie creation.
*
Expand Down
5 changes: 5 additions & 0 deletions src/Symfony/Component/Security/Http/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

6.3
---

* Add `RememberMeBadge` to `JsonLoginAuthenticator` and enable reading parameter in JSON request body

6.2
---

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ public function onSuccessfulLogin(LoginSuccessEvent $event): void
/** @var RememberMeBadge $badge */
$badge = $passport->getBadge(RememberMeBadge::class);
if (!$this->options['always_remember_me']) {
$parameter = ParameterBagUtils::getRequestParameterValue($event->getRequest(), $this->options['remember_me_parameter']);
if (!('true' === $parameter || 'on' === $parameter || '1' === $parameter || 'yes' === $parameter || true === $parameter)) {
$parameter = ParameterBagUtils::getRequestParameterValue($event->getRequest(), $this->options['remember_me_parameter'], $badge->parameters);
if (!filter_var($parameter, \FILTER_VALIDATE_BOOL)) {
$this->logger?->debug('Remember me disabled; request does not contain remember me parameter ("{parameter}").', ['parameter' => $this->options['remember_me_parameter']]);

return;
Expand Down
14 changes: 10 additions & 4 deletions src/Symfony/Component/Security/Http/ParameterBagUtils.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,22 +60,28 @@ public static function getParameterBagValue(ParameterBag $parameters, string $pa
*
* @throws InvalidArgumentException when the given path is malformed
*/
public static function getRequestParameterValue(Request $request, string $path): mixed
public static function getRequestParameterValue(Request $request, string $path, array $parameters = []): mixed
{
if (false === $pos = strpos($path, '[')) {
return $request->get($path);
return $parameters[$path] ?? $request->get($path);
}

$root = substr($path, 0, $pos);

if (null === $value = $request->get($root)) {
if (null === $value = $parameters[$root] ?? $request->get($root)) {
return null;
}

self::$propertyAccessor ??= PropertyAccess::createPropertyAccessor();

try {
return self::$propertyAccessor->getValue($value, substr($path, $pos));
$value = self::$propertyAccessor->getValue($value, substr($path, $pos));

if (null === $value && isset($parameters[$root]) && null !== $value = $request->get($root)) {
$value = self::$propertyAccessor->getValue($value, substr($path, $pos));
}

return $value;
} catch (AccessException) {
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,34 +33,55 @@ class CheckRememberMeConditionsListenerTest extends TestCase
protected function setUp(): void
{
$this->listener = new CheckRememberMeConditionsListener();
$this->request = Request::create('/login');
$this->request->request->set('_remember_me', true);
$this->response = new Response();
}

public function testSuccessfulLoginWithoutSupportingAuthenticator()
public function testSuccessfulHttpLoginWithoutSupportingAuthenticator()
{
$this->createHttpRequest();

$passport = $this->createPassport([]);

$this->listener->onSuccessfulLogin($this->createLoginSuccessfulEvent($passport));

$this->assertFalse($passport->hasBadge(RememberMeBadge::class));
}

public function testSuccessfulJsonLoginWithoutSupportingAuthenticator()
{
$this->createJsonRequest();

$passport = $this->createPassport([]);
$this->listener->onSuccessfulLogin($this->createLoginSuccessfulEvent($passport));

$this->assertFalse($passport->hasBadge(RememberMeBadge::class));
}

public function testSuccessfulLoginWithoutRequestParameter()
{
$this->request = Request::create('/login');
$passport = $this->createPassport();
$passport = $this->createPassport([new RememberMeBadge()]);

$this->listener->onSuccessfulLogin($this->createLoginSuccessfulEvent($passport));

$this->assertFalse($passport->getBadge(RememberMeBadge::class)->isEnabled());
}

public function testSuccessfulLoginWhenRememberMeAlwaysIsTrue()
public function testSuccessfulHttpLoginWhenRememberMeAlwaysIsTrue()
{
$this->createHttpRequest();

$passport = $this->createPassport();

$this->listener->onSuccessfulLogin($this->createLoginSuccessfulEvent($passport));

$this->assertTrue($passport->getBadge(RememberMeBadge::class)->isEnabled());
}

public function testSuccessfulJsonLoginWhenRememberMeAlwaysIsTrue()
{
$this->createJsonRequest();

$passport = $this->createPassport();
$listener = new CheckRememberMeConditionsListener(['always_remember_me' => true]);

$this->listener->onSuccessfulLogin($this->createLoginSuccessfulEvent($passport));

Expand All @@ -70,8 +91,10 @@ public function testSuccessfulLoginWhenRememberMeAlwaysIsTrue()
/**
* @dataProvider provideRememberMeOptInValues
*/
public function testSuccessfulLoginWithOptInRequestParameter($optInValue)
public function testSuccessfulHttpLoginWithOptInRequestParameter($optInValue)
{
$this->createHttpRequest();

$this->request->request->set('_remember_me', $optInValue);
$passport = $this->createPassport();

Expand All @@ -80,6 +103,20 @@ public function testSuccessfulLoginWithOptInRequestParameter($optInValue)
$this->assertTrue($passport->getBadge(RememberMeBadge::class)->isEnabled());
}

/**
* @dataProvider provideRememberMeOptInValues
*/
public function testSuccessfulJsonLoginWithOptInRequestParameter($optInValue)
{
$this->createJsonRequest(['_remember_me' => $optInValue]);

$passport = $this->createPassport([new RememberMeBadge(['_remember_me' => $optInValue])]);

$this->listener->onSuccessfulLogin($this->createLoginSuccessfulEvent($passport));

$this->assertTrue($passport->getBadge(RememberMeBadge::class)->isEnabled());
}

public static function provideRememberMeOptInValues()
{
yield ['true'];
Expand All @@ -89,13 +126,27 @@ public static function provideRememberMeOptInValues()
yield [true];
}

private function createHttpRequest(): void
{
$this->request = Request::create('/login');
$this->request->request->set('_remember_me', true);
$this->response = new Response();
}

private function createJsonRequest(array $content = ['_remember_me' => true]): void
{
$this->request = Request::create('/login', 'POST', [], [], [], [], json_encode($content));
$this->request->headers->add(['Content-Type' => 'application/json']);
$this->response = new Response();
}

private function createLoginSuccessfulEvent(Passport $passport)
{
return new LoginSuccessEvent($this->createMock(AuthenticatorInterface::class), $passport, $this->createMock(TokenInterface::class), $this->request, $this->response, 'main_firewall');
}

private function createPassport(array $badges = null)
{
return new SelfValidatingPassport(new UserBadge('test', fn ($username) => new InMemoryUser($username, null)), $badges ?? [new RememberMeBadge()]);
return new SelfValidatingPassport(new UserBadge('test', fn ($username) => new InMemoryUser($username, null)), $badges ?? [new RememberMeBadge(['_remember_me' => true])]);
}
}