8000 [Security] AuthenticatorManager to make "authenticators" first-class security by wouterj · Pull Request #33558 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Security] AuthenticatorManager to make "authenticators" first-class security #33558

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 30 commits into from
Apr 21, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
c321f4d
Created GuardAuthenticationManager to make Guard first-class Security
wouterj Sep 8, 2019
a6890db
Created HttpBasicAuthenticator and some Guard traits
wouterj Sep 8, 2019 8000
9b7fddd
Integrated GuardAuthenticationManager in the SecurityBundle
wouterj Sep 8, 2019
a172bac
Added FormLogin and Anonymous authenticators
wouterj Dec 13, 2019
526f756
Added GuardManagerListener
wouterj Dec 13, 2019
5013258
Add provider key in PreAuthenticationGuardToken
wouterj Jan 26, 2020
5efa892
Create a new core AuthenticatorInterface
wouterj Jan 26, 2020
fa4b3ec
Implemented password migration for the new authenticators
wouterj Jan 26, 2020
4c06236
Fixes after testing in Demo application
wouterj Jan 26, 2020
873b949
Mark new core authenticators as experimental
wouterj Jan 26, 2020
b923e4c
Enabled remember me for the GuardManagerListener
wouterj Jan 26, 2020
b14a5e8
Moved new authenticator to the HTTP namespace
wouterj Jan 26, 2020
999ec27
Refactor to an event based authentication approach
wouterj Feb 6, 2020
7859977
Removed all mentions of 'guard' in the new system
wouterj Feb 6, 2020
1c810d5
Added support for lazy firewalls
wouterj Feb 9, 2020
ddf430f
Added remember me functionality
wouterj Feb 12, 2020
09bed16
Only load old manager if new system is disabled
wouterj Feb 22, 2020
44cc76f
Use one AuthenticatorManager per firewall
wouterj Feb 29, 2020
bf1a452
Merge AuthenticatorManager and AuthenticatorHandler
wouterj Mar 1, 2020
60d396f
Added automatically CSRF protected authenticators
wouterj Mar 1, 2020
59f49b2
Rename AuthenticatingListener
wouterj Mar 7, 2020
6b9d78d
Added tests
wouterj Mar 7, 2020
ba3754a
Differentiate between interactive and non-interactive authenticators
wouterj Mar 13, 2020
f5e11e5
Reverted changes to the Guard component
wouterj Mar 14, 2020
95edc80
Added pre-authenticated authenticators (X.509 & REMOTE_USER)
wouterj Mar 14, 2020
7ef6a7a
Use the firewall event dispatcher
wouterj Apr 4, 2020
0fe5083
Added JSON login authenticator
wouterj Apr 5, 2020
9ea32c4
Also use authentication failure/success handlers in FormLoginAuthenti…
wouterj Apr 6, 2020
50224aa
Introduce Passport & Badges to extend authenticators
wouterj Apr 9, 2020
b1e040f
Rename providerKey to firewallName for more consistent naming
wouterj Apr 10, 2020
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
Added JSON login authenticator
  • Loading branch information
wouterj committed Apr 20, 2020
commit 0fe5083a3e29af82418e33f3073137c921c5f707
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
class JsonLoginFactory extends AbstractFactory
class JsonLoginFactory extends AbstractFactory implements AuthenticatorFactoryInterface
{
public function __construct()
{
Expand Down Expand Up @@ -96,4 +96,18 @@ protected function createListener(ContainerBuilder $container, string $id, array

return $listenerId;
}

public function createAuthenticator(ContainerBuilder $container, string $id, array $config, string $userProviderId)
{
$authenticatorId = 'security.authenticator.json_login.'.$id;
$options = array_intersect_key($config, $this->options);
$container
->setDefinition($authenticatorId, new ChildDefinition('security.authenticator.json_login'))
->replaceArgument(1, new Reference($userProviderId))
->replaceArgument(2, isset($config['success_handler']) ? new Reference($this->createAuthenticationSuccessHandler($container, $id, $config)) : null)
->replaceArgument(3, isset($config['failure_handler']) ? new Reference($this->createAuthenticationFailureHandler($container, $id, $config)) : null)
->replaceArgument(4, $options);

return $authenticatorId;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,17 @@
<argument type="abstract">options</argument>
</service>

<service id="security.authenticator.json_login"
class="Symfony\Component\Security\Http\Authenticator\JsonLoginAuthenticator"
abstract="true">
<argument type="service" id="security.http_utils" />
<argument type="abstract">user provider</argument>
<argument type="abstract">authentication success handler</argument>
<argument type="abstract">authentication failure handler</argument>
<argument type="abstract">options</argument>
<argument type="service" id="property_accessor" on-invalid="null" />
</service>

<service id="security.authenticator.anonymous"
class="Symfony\Component\Security\Http\Authenticator\AnonymousAuthenticator"
abstract="true">
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
<?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\Authenticator;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\PropertyAccess\Exception\AccessException;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Http\HttpUtils;

/**
* Provides a stateless implementation of an authentication via
* a JSON document composed of a username and a password.
*
* @author Kévin Dunglas <dunglas@gmail.com>
* @author Wouter de Jong <wouter@wouterj.nl>
*
* @final
* @experimental in 5.1
*/
class JsonLoginAuthenticator implements InteractiveAuthenticatorInterface, PasswordAuthenticatedInterface
{
private $options;
private $httpUtils;
private $userProvider;
private $propertyAccessor;
private $successHandler;
private $failureHandler;

public function __construct(HttpUtils $httpUtils, UserProviderInterface $userProvider, ?AuthenticationSuccessHandlerInterface $successHandler = null, ?AuthenticationFailureHandlerInterface $failureHandler = null, array $options = [], ?PropertyAccessorInterface $propertyAccessor = null)
{
$this->options = array_merge(['username_path' => 'username', 'password_path' => 'password'], $options);
$this->httpUtils = $httpUtils;
$this->successHandler = $successHandler;
$this->failureHandler = $failureHandler;
$this->userProvider = $userProvider;
$this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
}

public function supports(Request $request): ?bool
{
if (false === strpos($request->getRequestFormat(), 'json') && false === strpos($request->getContentType(), 'json')) {
return false;
}

if (isset($this->options['check_path']) && !$this->httpUtils->checkRequestPath($request, $this->options['check_path'])) {
return false;
}

return true;
}

public function getCredentials(Request $request)
{
$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']);

if (!\is_string($credentials['username'])) {
throw new BadRequestHttpException(sprintf('The key "%s" must be a string.', $this->options['username_path']));
}

if (\strlen($credentials['username']) > Security::MAX_USERNAME_LENGTH) {
throw new BadCredentialsException('Invalid username.');
}
} catch (AccessException $e) {
throw new BadRequestHttpException(sprintf('The key "%s" must be provided.', $this->options['username_path']), $e);
}

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

if (!\is_string($credentials['password'])) {
throw new BadRequestHttpException(sprintf('The key "%s" must be a string.', $this->options['password_path']));
}
} catch (AccessException $e) {
throw new BadRequestHttpException(sprintf('The key "%s" must be provided.', $this->options['password_path']), $e);
}

return $credentials;
}

public function getUser($credentials): ?UserInterface
{
return $this->userProvider->loadUserByUsername($credentials['username']);
}

public function getPassword($credentials): ?string
{
return $credentials['password'];
}

public function createAuthenticatedToken(UserInterface $user, string $providerKey): TokenInterface
{
return new UsernamePasswordToken($user, null, $providerKey, $user->getRoles());
}

public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $providerKey): ?Response
{
if (null === $this->successHandler) {
return null; // let the original request continue
}

return $this->successHandler->onAuthenticationSuccess($request, $token);
}

public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
if (null === $this->failureHandler) {
return new JsonResponse(['error' => $exception->getMessageKey()], JsonResponse::HTTP_UNAUTHORIZED);
}

return $this->failureHandler->onAuthenticationFailure($request, $exception);
}

public function isInteractive(): bool
{
return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
<?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\Tests\Authenticator;

use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Http\Authenticator\JsonLoginAuthenticator;
use Symfony\Component\Security\Http\HttpUtils;

class JsonLoginAuthenticatorTest extends TestCase
{
private $userProvider;
/** @var JsonLoginAuthenticator */
private $authenticator;

protected function setUp(): void
{
$this->userProvider = $this->createMock(UserProviderInterface::class);
}

/**
* @dataProvider provideSupportData
*/
public function testSupport($request)
{
$this->setUpAuthenticator();

$this->assertTrue($this->authenticator->supports($request));
}

public function provideSupportData()
{
yield [new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json'], '{"username": "dunglas", "password": "foo"}')];

$request = new Request([], [], [], [], [], [], '{"username": "dunglas", "password": "foo"}');
$request->setRequestFormat('json-ld');
yield [$request];
}

/**
* @dataProvider provideSupportsWithCheckPathData
*/
public function testSupportsWithCheckPath($request, $result)
{
$this->setUpAuthenticator(['check_path' => '/api/login']);

$this->assertSame($result, $this->authenticator->supports($request));
}

public function provideSupportsWithCheckPathData()
{
yield [Request::create('/api/login', 'GET', [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json']), true];
yield [Request::create('/login', 'GET', [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json']), false];
}

public function testGetCredentials()
{
$this->setUpAuthenticator();

$request = new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json'], '{"username": "dunglas", "password": "foo"}');
$this->assertEquals(['username' => 'dunglas', 'password' => 'foo'], $this->authenticator->getCredentials($request));
}

public function testGetCredentialsCustomPath()
{
$this->setUpAuthenticator([
'username_path' => 'authentication.username',
'password_path' => 'authentication.password',
]);

$request = new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json'], '{"authentication": {"username": "dunglas", "password": "foo"}}');
$this->assertEquals(['username' => 'dunglas', 'password' => 'foo'], $this->authenticator->getCredentials($request));
}

/**
* @dataProvider provideInvalidGetCredentialsData
*/
public function testGetCredentialsInvalid($request, $errorMessage, $exceptionType = BadRequestHttpException::class)
{
$this->expectException($exceptionType);
$this->expectExceptionMessage($errorMessage);

$this->setUpAuthenticator();

$this->authenticator->getCredentials($request);
}

public function provideInvalidGetCredentialsData()
{
$request = new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json']);
yield [$request, 'Invalid JSON.'];

$request = new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json'], '{"usr": "dunglas", "password": "foo"}');
yield [$request, 'The key "username" must be provided'];

$request = new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json'], '{"username": "dunglas", "pass": "foo"}');
yield [$request, 'The key "password" must be provided'];

$request = new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json'], '{"username": 1, "password": "foo"}');
yield [$request, 'The key "username" must be a string.'];

$request = new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json'], '{"username": "dunglas", "password": 1}');
yield [$request, 'The key "password" must be a string.'];

$username = str_repeat('x', Security::MAX_USERNAME_LENGTH + 1);
$request = new Request([], [], [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json'], sprintf('{"username": "%s", "password": 1}', $username));
yield [$request, 'Invalid username.', BadCredentialsException::class];
}

private function setUpAuthenticator(array $options = [])
{
$this->authenticator = new JsonLoginAuthenticator(new HttpUtils(), $this->userProvider, null, null, $options);
}
}
0