8000 Adding a new RefreshableRolesTokenInterface to refresh security roles by weaverryan · Pull Request #24331 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

Adding a new RefreshableRolesTokenInterface to refresh security roles #24331

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 3 commits into from
Closed
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
Changing behavior so that roles are only refreshed if the token requests
it

By default, AbstractToken (and its sub-classes), have a mechanism to
check if any extra tokens were added, beyond the user tokens. If
there are none, then the roles are refreshed. If there are some,
then they are not.
  • Loading branch information
weaverryan committed Sep 26, 2017
commit 87d2826871d308a7c1389e065e686b74fb2998e1
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\Bundle\SecurityBundle\Tests\Functional;

use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;

class RefreshableRolesTest extends WebTestCase
{
public function testRolesAreRefreshed()
{
// log them in!
$client = $this->createAuthenticatedClient('cool_user');

// refresh the page, roles have not changed yet
$client->request('GET', '/profile');
$rolesData = $client->getProfile()->getCollector('security')->getRoles();
$this->assertCount(1, $rolesData);
$this->assertEquals('ROLE_ORIGINAL', $rolesData[0]);

// this will cause the refreshed user to have these new roles
$client->request('GET', '/profile?new_role=ROLE_NEW');
$rolesData = $client->getProfile()->getCollector('security')->getRoles();
$this->assertCount(1, $rolesData);
$this->assertEquals('ROLE_NEW', $rolesData[0]);

// the change should be persistent
$client->request('GET', '/profile');
$rolesData = $client->getProfile()->getCollector('security')->getRoles();
$this->assertCount(1, $rolesData);
$this->assertEquals('ROLE_NEW', $rolesData[0]);
}

private function createAuthenticatedClient($username)
{
$client = $this->createClient(array('test_case' => 'StandardFormLogin', 'root_config' => 'refreshable_roles.yml'));
$client->followRedirects(true);

$form = $client->request('GET', '/login')->selectButton('login')->form();
$form['_username'] = $username;
$form['_password'] = 'test';
$client->submit($form);

return $client;
}
}

class RefreshableRolesUserProvider implements UserProviderInterface
{
private $requestStack;

public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}

public function loadUserByUsername($username)
{
return new RefreshableUser($username, array('ROLE_ORIGINAL'));
}

public function refreshUser(UserInterface $user)
{
$request = $this->requestStack->getCurrentRequest();
// a sneaky way of faking the stored user's roles being changed
if ($request->query->has('new_role')) {
$user->setRoles(array($request->query->get('new_role')));
}

return $user;
}

public function supportsClass($class)
{
return RefreshableUser::class === $class;
}
}

class RefreshableUser implements UserInterface
{
private $username;
private $roles;

public function __construct($username, array $roles)
{
$this->username = $username;
$this->roles = $roles;
}

public function getUsername()
{
return $this->username;
}

public function getRoles()
{
return $this->roles;
}

public function setRoles($roles)
{
$this->roles = $roles;
}

public function getPassword()
{
return 'test';
}

public function getSalt()
{
}

public function eraseCredentials()
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
imports:
- { resource: ./../config/default.yml }

services:
refreshable_roles_user_provider:
class: Symfony\Bundle\SecurityBundle\Tests\Functional\RefreshableRolesUserProvider
arguments: ['@request_stack']

security:
encoders:
Symfony\Bundle\SecurityBundle\Tests\Functional\RefreshableUser: plaintext

providers:
all_users:
id: refreshable_roles_user_provider

firewalls:
# This firewall doesn't make sense in combination with the rest of the
# configuration file, but it's here for testing purposes (do not use
# this file in a real world scenario though)
login_form:
pattern: ^/login$
security: false

default:
form_login:
check_path: /login_check
default_target_path: /profile
anonymous: ~
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ abstract class AbstractToken implements TokenInterface, RefreshableRolesTokenInt
private $roles = array();
private $authenticated = false;
private $attributes = array();
private $shouldUpdateRoles = false;

/**
* Constructor.
Expand Down Expand Up @@ -235,6 +236,14 @@ public function updateRoles(array $roles)
}
}

/**
* {@inheritdoc}
*/
public function shouldUpdateRoles()
{
return $this->shouldUpdateRoles;
}

/**
* {@inheritdoc}
*/
Expand All @@ -251,6 +260,18 @@ public function __toString()
return sprintf('%s(user="%s", authenticated=%s, roles="%s")', $class, $this->getUsername(), json_encode($this->authenticated), implode(', ', $roles));
}

/**
* Call this from a sub-class if you want the token's roles
* to be updated from UserInterface::getRoles() on each
* page refresh (when using session-based authentication).
*
* @param bool $shouldUpdateRoles
*/
protected function setShouldUpdateRoles($shouldUpdateRoles)
{
$this->shouldUpdateRoles = $shouldUpdateRoles;
}

private function hasUserChanged(UserInterface $user)
{
if (!($this->user instanceof UserInterface)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\Security\Core\Authentication\Token;

use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\User\UserInterface;

/ 1E0A **
* AnonymousToken represents an anonymous token.
Expand All @@ -36,6 +37,8 @@ public function __construct($secret, $user, array $roles = array())
$this->secret = $secret;
$this->setUser($user);
$this->setAuthenticated(true);

$this->setShouldUpdateRoles($user instanceof UserInterface && $user->getRoles() === $roles);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

namespace Symfony\Component\Security\Core\Authentication\Token;

use Symfony\Component\Security\Core\User\UserInterface;

/**
* PreAuthenticatedToken implements a pre-authenticated token.
*
Expand Down Expand Up @@ -44,6 +46,8 @@ public function __construct($user, $credentials, $providerKey, array $roles = ar
if ($roles) {
$this->setAuthenticated(true);
}

$this->setShouldUpdateRoles($user instanceof UserInterface && $user->getRoles() === $roles);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,15 @@ interface RefreshableRolesTokenInterface
* @param array $roles An array of roles
*/
public function updateRoles(array $roles);

/**
* Returns whether or not roles *should* be updated on this token.
*
* This can be useful if your token is adding custom roles,
* and so you purposely do not want the roles in the token to
* be automatically reset.
*
* @return bool
*/
public function shouldUpdateRoles();
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ public function __construct(UserInterface $user, $providerKey, $secret)

$this->setUser($user);
parent::setAuthenticated(true);
$this->setShouldUpdateRoles(true);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

namespace Symfony\Component\Security\Core\Authentication\Token;

use Symfony\Component\Security\Core\User\UserInterface;

/**
* UsernamePasswordToken implements a username and password token.
*
Expand Down Expand Up @@ -44,6 +46,8 @@ public function __construct($user, $credentials, $providerKey, array $roles = ar
$this->providerKey = $providerKey;

parent::setAuthenticated(count($roles) > 0);

$this->setShouldUpdateRoles($user instanceof UserInterface && $user->getRoles() === $roles);
Copy link
Contributor

Choose a reason for hiding this comment

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

Is this is expected... this affects all tokens today no? Should we optin thru config instead?

Copy link
Member Author

Choose a reason for hiding this comment

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

This was my way of trying to safely opt everyone in automatically... but I don't think that's possible anymore, thanks to #24331 (comment)

So yea, I think we'll need to have a way to opt into this somehow...

}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public function testAuthenticate()
{
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user
->expects($this->once())
->expects($this->atLeastOnce())
->method('getRoles')
->will($this->returnValue(array()))
;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ public function testAuthenticateWhenPostCheckAuthenticationFailsWithHideFalse()
public function testAuthenticate()
{
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user->expects($this->once())
$user->expects($this->atLeastOnce())
->method('getRoles')
->will($this->returnValue(array('ROLE_FOO')))
;
Expand Down Expand Up @@ -193,7 +193,7 @@ public function testAuthenticate()
public function testAuthenticateWithPreservingRoleSwitchUserRole()
{
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user->expects($this->once())
$user->expects($this->atLeastOnce())
->method('getRoles')
->will($this->returnValue(array('ROLE_FOO')))
;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ public function __construct(UserInterface $user, $providerKey, array $roles)
// this token is meant to be used after authentication success, so it is always authenticated
// you could set it as non authenticated later if you need to
parent::setAuthenticated(true);

$this->setShouldUpdateRoles($user instanceof UserInterface && $user->getRoles() === $roles);
}

/**
Expand Down
15 changes: 14 additions & 1 deletion src/Symfony/Component/Security/Http/Firewall/ContextListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,14 @@ class ContextListener implements ListenerInterface
private $tokenStorage;
private $contextKey;
private $sessionKey;
private $refreshableRolesSessionKey;
private $logger;
private $userProviders;
private $dispatcher;
private $registered;
private $trustResolver;
private $logoutOnUserChange = false;
private $refreshedToken;

/**
* @param TokenStorageInterface $tokenStorage
Expand All @@ -65,6 +67,8 @@ public function __construct(TokenStorageInterface $tokenStorage, $userProviders,
$this->userProviders = $userProviders;
$this->contextKey = $contextKey;
$this->sessionKey = '_security_'.$contextKey;
$this->refreshableRolesSessionKey = $this->sessionKey.'_refreshable_roles';

$this->logger = $logger;
$this->dispatcher = $dispatcher;
$this->trustResolver = $trustResolver ?: new AuthenticationTrustResolver(AnonymousToken::class, RememberMeToken::class);
Expand Down Expand Up @@ -120,14 +124,16 @@ public function handle(GetResponseEvent $event)
$token = null;
}

if ($token instanceof RefreshableRolesTokenInterface && $token->getUser() instanceof UserInterface) {
// see if this token wants the roles refreshed from the User
if ($session->get($this->refreshableRolesSessionKey) && $token->getUser() instanceof UserInterface) {
if (null !== $this->logger) {
$this->logger->debug('Refreshing token roles from the User object');
}

$token->updateRoles($token->getUser()->getRoles());
}

$this->refreshedToken = $token;
$this->tokenStorage->setToken($token);
}

E03C Expand Down Expand Up @@ -155,13 +161,20 @@ public function onKernelResponse(FilterResponseEvent $event)
if ((null === $token = $this->tokenStorage->getToken()) || $this->trustResolver->isAnonymous($token)) {
if ($request->hasPreviousSession()) {
$session->remove($this->sessionKey);
$session->remove($this->refreshableRolesSessionKey);
}
} else {
$session->set($this->sessionKey, serialize($token));

if (null !== $this->logger) {
$this->logger->debug('Stored the security token in the session.', array('key' => $this->sessionKey));
}

// if the token changed, then re-set the refreshable key
if ($token !== $this->refreshedToken) {
$shouldUpdateRoles = $token instanceof RefreshableRolesTokenInterface && $token->shouldUpdateRoles();
$session->set($this->refreshableRolesSessionKey, $shouldUpdateRoles);
}
Copy link
Member Author

Choose a reason for hiding this comment

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

This was a tricky part. The return value from shouldUpdateRoles() is not serialized to the session (i.e. it's not in AbstractToken::serialize(). This is done for BC: we can't change serialize() & unserialize() to include this.

So, we instead store this value in a different session key. This logic only sets it if the token has changed. Basically, we want to set this session key during the original request when authentication occurred (that's when we know that shouldUpdateRoles() is accurate). By checking to see if the token changed, we're effectively accomplishing that.

This was the weirdest / hackiest part of this PR. I'm open to suggestions.

Copy link
Contributor

Choose a reason for hiding this comment

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

If your upgrading there is a big chance you already need to clear existing session data. So this change should be acceptable.

}
}

Expand Down
Loading
0