Skip to content

Commit

Permalink
Load users in Symfony resource provider
Browse files Browse the repository at this point in the history
Allows the token to contain not just the username but the actual user
object, using a user provider
Also the token will have roles from the user
  • Loading branch information
mcfedr committed Aug 9, 2017
1 parent d923b94 commit fb5e140
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use AuthBucket\OAuth2\Symfony\Component\Security\Core\Authentication\Token\AccessToken;
use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;

/**
* ResourceProvider implements OAuth2 resource endpoint authentication.
Expand All @@ -29,19 +30,22 @@ class ResourceProvider implements AuthenticationProviderInterface
protected $resourceType;
protected $scopeRequired;
protected $options;
protected $userProvider;

public function __construct(
$providerKey,
ResourceTypeHandlerFactoryInterface $resourceTypeHandlerFactory,
$resourceType = 'model',
array $scopeRequired = [],
array $options = []
array $options = [],
UserProviderInterface $userProvider = null
) {
$this->providerKey = $providerKey;
$this->resourceTypeHandlerFactory = $resourceTypeHandlerFactory;
$this->resourceType = $resourceType;
$this->scopeRequired = $scopeRequired;
$this->options = $options;
$this->userProvider = $userProvider;
}

public function authenticate(TokenInterface $token)
Expand All @@ -68,6 +72,13 @@ public function authenticate(TokenInterface $token)
}
}

$user = null;
$roles = $token->getRoles();
if ($this->userProvider) {
$user = $this->userProvider->loadUserByUsername($accessToken->getUsername());
$roles = array_merge($roles, $user->getRoles());
}

$tokenAuthenticated = new AccessToken(
$this->providerKey,
$accessToken->getAccessToken(),
Expand All @@ -76,9 +87,9 @@ public function authenticate(TokenInterface $token)
$accessToken->getUsername(),
$accessToken->getExpires(),
$accessToken->getScope(),
$token->getRoles()
$roles,
$user ? $user : $accessToken->getUsername()
);
$tokenAuthenticated->setUser($accessToken->getUsername());

return $tokenAuthenticated;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ public function __construct(
$username = '',
$expires = '',
array $scope = [],
array $roles = []
array $roles = [],
$user = null
) {
parent::__construct($roles);

Expand All @@ -48,6 +49,9 @@ public function __construct(
$this->username = $username;
$this->expires = $expires;
$this->scope = $scope;
if (null !== $user) {
$this->setUser($user);
}

parent::setAuthenticated(count($roles) > 0);
}
Expand Down

0 comments on commit fb5e140

Please sign in to comment.