Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[DX] Ability to authentication a User directly #11320

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

Closed
wants to merge 9 commits into from
Closed
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
11 changes: 11 additions & 0 deletions src/Symfony/Bundle/SecurityBundle/Resources/config/security.xml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@
<parameter key="security.validator.user_password.class">Symfony\Component\Security\Core\Validator\Constraints\UserPasswordValidator</parameter>

<parameter key="security.expression_language.class">Symfony\Component\Security\Core\Authorization\ExpressionLanguage</parameter>

<parameter key="security.login_manager.class">Symfony\Component\Security\Http\Login\LoginManager</parameter>
</parameters>

<services>
Expand Down Expand Up @@ -151,5 +153,14 @@
<argument type="service" id="security.context" />
<argument type="service" id="security.encoder_factory" />
</service>

<!-- Login Manager -->
<service id="security.login_manager" class="%security.login_manager.class%">
<argument type="service" id="security.context" />
<argument type="service" id="security.user_checker" />
<argument type="service" id="request_stack" />
<argument type="service" id="security.authentication.session_strategy" />
<argument type="service" id="security.rememberme.resolver" />
</service>
</services>
</container>
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
<parameter key="security.authentication.rememberme.services.simplehash.class">Symfony\Component\Security\Http\RememberMe\TokenBasedRememberMeServices</parameter>

<parameter key="security.rememberme.response_listener.class">Symfony\Component\Security\Http\RememberMe\ResponseListener</parameter>

<parameter key="security.rememberme.resolver.class">Symfony\Bundle\SecurityBundle\Security\Http\RememberMe\RememberMeServicesResolver</parameter>
</parameters>

<services>
Expand Down Expand Up @@ -57,6 +59,10 @@
<service id="security.rememberme.response_listener" class="%security.rememberme.response_listener.class%">
<tag name="kernel.event_subscriber" />
</service>

<service id="security.rememberme.resolver" class="%security.rememberme.resolver.class%">
<argument type="service" id="service_container" />
</service>
</services>

</container>
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\SecurityBundle\Security\Http\RememberMe;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;
use Symfony\Component\Security\Http\RememberMe\RememberMeServicesResolverInterface;

class RememberMeServicesResolver implements RememberMeServicesResolverInterface
{
/**
* @var \Symfony\Component\DependencyInjection\ContainerInterface
*/
private $serviceContainer;

/**
* @param ContainerInterface $serviceContainer
*/
public function __construct(ContainerInterface $serviceContainer)
{
$this->serviceContainer = $serviceContainer;
}

/**
* @param $providerKey
* @return null|RememberMeServicesInterface
*/
public function resolve($providerKey)
{
$rememberMeServices = null;
if ($this->serviceContainer->has('security.authentication.rememberme.services.persistent.'.$providerKey)) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I remember correctly these services are marked private. We also have (had?) this problem in the FOSUserBundle.

$rememberMeServices = $this->serviceContainer->get('security.authentication.rememberme.services.persistent.'.$providerKey);
} elseif ($this->serviceContainer->has('security.authentication.rememberme.services.simplehash.'.$providerKey)) {
$rememberMeServices = $this->serviceContainer->get('security.authentication.rememberme.services.simplehash.'.$providerKey);
}

if ($rememberMeServices instanceof RememberMeServicesInterface) {
return $rememberMeServices;
}

return;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\LoginManagerBundle\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\DependencyInjection\ContainerAware;

class LoginController extends ContainerAware
{
public function loginAction()
{
$user = $this->container->get('security.user.provider.concrete.in_memory')->loadUserByUsername('norzechowicz');
$this->container->get('security.login_manager')->loginUser('secured_area', $user);

return new Response();
}

public function loginCheckAction()
{
return new Response('', 400);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\LoginManagerBundle\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\DependencyInjection\ContainerAware;

class SecuredController extends ContainerAware
{
public function indexAction()
{
return new Response("Secured area");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\LoginManagerBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class LoginManagerBundle extends Bundle
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
login:
path: /login
defaults: { _controller: LoginManagerBundle:Login:login }

login_check:
path: /login_check
defaults: { _controller: LoginManagerBundle:Login:loginCheck }

secured_index:
path: /secured/index
defaults: { _controller: LoginManagerBundle:Secured:index }


Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\SecurityBundle\Tests\Functional;

/**
* @group functional
*/
class LoginManagerTestCase extends WebTestCase
{
public function testLoginUserInController()
{
$client = $this->createClient(array('test_case' => 'LoginManager'));

// Avoid to follow redirects. If we follow this redirect, the user
// will be logged in automatically
$client->setMaxRedirects(-1);
$client->request('GET', '/secured/index');
$this->assertRedirect($client->getResponse(), '/login');

// Access to '/login' route to login the user automatically
$client->request('GET', '/login');
$client->request('GET', '/secured/index');
$this->assertEquals('Secured area', $client->getResponse()->getContent());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

return array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\LoginManagerBundle\LoginManagerBundle(),
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
imports:
- { resource: ./../config/default.yml }

security:
encoders:
Symfony\Component\Security\Core\User\User: plaintext

providers:
in_memory:
memory:
users:
norzechowicz: { password: test, roles: [ROLE_USER] }

firewalls:
secured_area:
pattern: ^/
form_login:
check_path: /login_check
default_target_path: /secured/index
anonymous: ~

access_control:
- { path: ^/login$, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: .*, roles: ROLE_USER }
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
_csrf_form_login_bundle:
resource: @LoginManagerBundle/Resources/config/routing.yml
107 changes: 107 additions & 0 deletions src/Symfony/Component/Security/Http/Login/LoginManager.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Security\Http\Login;

use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Http\RememberMe\RememberMeServicesResolverInterface;
use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategyInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;

class LoginManager
{
/**
* @var SecurityContextInterface
*/
private $securityContext;

/**
* @var UserCheckerInterface
*/
private $userChecker;

/**
* @var RequestStack
*/
private $requestStack;

/**
* @var SessionAuthenticationStrategyInterface
*/
private $sessionAuthenticationStrategy;

/**

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[minor] Empty line missing

* @var RememberMeServicesResolverInterface
*/
private $rememberMeServicesResolver;

/**
* @param SecurityContextInterface $securityContext
* @param UserCheckerInterface $userChecker
* @param RequestStack $requestStack
* @param SessionAuthenticationStrategyInterface $sessionAuthenticationStrategy
* @param RememberMeServicesResolverInterface $rememberMeServicesResolver
*/
public function __construct(SecurityContextInterface $securityContext, UserCheckerInterface $userChecker, RequestStack $requestStack, SessionAuthenticationStrategyInterface $sessionAuthenticationStrategy, RememberMeServicesResolverInterface $rememberMeServicesResolver)
{
$this->securityContext = $securityContext;
$this->userChecker = $userChecker;
$this->requestStack = $requestStack;
$this->sessionAuthenticationStrategy = $sessionAuthenticationStrategy;
$this->rememberMeServicesResolver = $rememberMeServicesResolver;
}

/**
* @param $firewallName
* @param UserInterface $user
* @param Response $response
*/
public function loginUser($firewallName, UserInterface $user, Response $response = null)
{
$this->userChecker->checkPreAuth($user);
$this->userChecker->checkPostAuth($user);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't the method checkPreAuth be called previously?

$token = $this->createToken($firewallName, $user);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't we check if the token has been authenticated?

if (!$token->isAuthenticated()) {
    throw new AuthenticationException("Unauthenticated token.");
}


if (!$token->isAuthenticated()) {
throw new AuthenticationException("Unauthenticated token");
}

$request = $this->requestStack->getMasterRequest();
if (null !== $request) {
$this->sessionAuthenticationStrategy->onAuthentication($request, $token);

if (null !== $response) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could let you remove one level of indentation:

    if (null !== $response && ($rememberMeServices = $this->rememberMeServicesResolver->resolve($firewallName)) {

$rememberMeServices = $this->rememberMeServicesResolver->resolve($firewallName);

if (null !== $rememberMeServices) {
$rememberMeServices->loginSuccess($request, $response, $token);
}
}
}

$this->securityContext->setToken($token);
}

/**
* @param $firewall
* @param UserInterface $user
* @return UsernamePasswordToken
*/
protected function createToken($firewall, UserInterface $user)
{
return new UsernamePasswordToken($user, null, $firewall, $user->getRoles());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace Symfony\Component\Security\Http\RememberMe;

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

interface RememberMeServicesResolverInterface
{
/**
* @param $providerKey
* @return null|RememberMeServicesInterface
*/
public function resolve($providerKey);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't see the need for an interface.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you sure about that? Symfony\Bundle\SecurityBundle\Security\Http\RememberMe\RememberMeServicesResolver is just an implementation that resolve RememberMeServices from symfony2 service container. There is also FakeRememberMeServicesResolver just for testing purpose but there also might be a RememberMeServicesResolver implementation that resolves RememberMeServices from different than sf2 service container or something like that. Correct me please if I'm wrong.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For FakeRememberMeServicesResolver, was there a reason you didn't just mock it in the test?

And if you'd like to replace the RememberMeServicesResolver, you could still sub-class it obviously. It's only used with this new LoginManager, which is meant just as a helper service anyways.

I can see it either way, but I don't think we really lose anything with removing the interface.

}
Loading