Skip to content

Commit

Permalink
reviewed authenticator, added SelfValidatedOAuthPassport, made refres…
Browse files Browse the repository at this point in the history
…hToken function public, so we can refresh access token from outside (Listener), login to oauth instance with a LoginForm - 'password' grand, etc
  • Loading branch information
gassan committed Dec 7, 2021
1 parent 89d7868 commit 122c67d
Show file tree
Hide file tree
Showing 6 changed files with 153 additions and 61 deletions.
18 changes: 13 additions & 5 deletions HWIOAuthBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@
use HWI\Bundle\OAuthBundle\DependencyInjection\HWIOAuthExtension;
use HWI\Bundle\OAuthBundle\DependencyInjection\Security\Factory\OAuthAuthenticatorFactory;
use HWI\Bundle\OAuthBundle\DependencyInjection\Security\Factory\OAuthFactory;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\AuthenticatorFactoryInterface;
use Symfony\Bundle\SecurityBundle\DependencyInjection\SecurityExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface;

/**
* @author Geoffrey Bachelet <geoffrey.bachelet@gmail.com>
Expand All @@ -37,11 +37,19 @@ public function build(ContainerBuilder $container)
/** @var SecurityExtension $extension */
$extension = $container->getExtension('security');

// Symfony < 5.4 BC layer
if (interface_exists(AuthenticationProviderInterface::class)) {
$extension->addSecurityListenerFactory(new OAuthFactory()); // @phpstan-ignore-this-line Symfony < 5.4 BC layer
// Symfony < 5.1 BC layer: support new Authenticator-based security system in Symfony 5.1+
// and old security system in all Symfony versions.
if (interface_exists(AuthenticatorFactoryInterface::class)) {
if (method_exists($extension, 'addAuthenticatorFactory')) {
$extension->addAuthenticatorFactory(new OAuthAuthenticatorFactory());
} else {
/*
* @deprecated since Symfony 5.4, use "addAuthenticatorFactory()" instead
*/
$extension->addSecurityListenerFactory(new OAuthAuthenticatorFactory());
}
} else {
$extension->addAuthenticatorFactory(new OAuthAuthenticatorFactory());
$extension->addSecurityListenerFactory(new OAuthFactory());
}

$container->addCompilerPass(new ResourceOwnerMapCompilerPass());
Expand Down
8 changes: 6 additions & 2 deletions Security/Core/Authentication/Token/AbstractOAuthToken.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,9 @@ public function __construct($accessToken, array $roles = [])

$this->setRawToken($accessToken);

// required for compatibility with Symfony 5.4
// @deprecated since Symfony 5.4
if (method_exists($this, 'setAuthenticated')) {
parent::setAuthenticated(\count($roles) > 0, false);
$this->setAuthenticated(\count($roles) > 0, false);
}
}

Expand Down Expand Up @@ -112,6 +112,10 @@ public function __unserialize(array $data): void
}
}

public function copyPersistentDataTo(self $token): void
{
}

/**
* {@inheritdoc}
*/
Expand Down
134 changes: 81 additions & 53 deletions Security/Http/Authenticator/OAuthAuthenticator.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use HWI\Bundle\OAuthBundle\Security\Core\Authentication\Token\OAuthToken;
use HWI\Bundle\OAuthBundle\Security\Core\Exception\OAuthAwareExceptionInterface;
use HWI\Bundle\OAuthBundle\Security\Core\User\OAuthAwareUserProviderInterface;
use HWI\Bundle\OAuthBundle\Security\Http\Authenticator\Passport\SelfValidatedOAuthPassport;
use HWI\Bundle\OAuthBundle\Security\Http\ResourceOwnerMapInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
Expand All @@ -28,9 +29,7 @@
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
use Symfony\Component\Security\Http\HttpUtils;

Expand All @@ -50,10 +49,6 @@ final class OAuthAuthenticator implements AuthenticatorInterface, Authentication
*/
private array $checkPaths;

private ?array $rawToken = null;
private ?string $resourceOwnerName = null;
private ?string $refreshToken = null;
private ?int $createdAt = null;
private array $options;

public function __construct(
Expand Down Expand Up @@ -125,8 +120,40 @@ public function authenticate(Request $request): Passport
$token = new OAuthToken($accessToken);
$token->setResourceOwnerName($resourceOwner->getName());

return new SelfValidatedOAuthPassport($this->refreshToken($token));
}

/**
* This function can be used for refreshing an expired token
* or for custom "password grant" authenticator, if site owner also owns oauth instance.
*
* @template T of OAuthToken
*
* @param T $token
*
* @return T
*/
public function refreshToken(OAuthToken $token): OAuthToken
{
$resourceOwner = $this->resourceOwnerMap->getResourceOwnerByName($token->getResourceOwnerName());

if ($token->isExpired()) {
$token = $this->refreshToken($token, $resourceOwner);
$expiredToken = $token;
if ($refreshToken = $expiredToken->getRefreshToken()) {
$tokenClass = \get_class($expiredToken);
$token = new $tokenClass($resourceOwner->refreshAccessToken($refreshToken));
$token->setResourceOwnerName($expiredToken->getResourceOwnerName());
if (!$token->getRefreshToken()) {
$token->setRefreshToken($expiredToken->getRefreshToken());
}
$expiredToken->copyPersistentDataTo($token);
} else {
// if you cannot refresh token, you do not need to make user_info request to oauth-resource
if ($expiredToken->getUser()) {
return $expiredToken;
}
}
unset($expiredToken);
}

$userResponse = $resourceOwner->getUserInformation($token->getRawToken());
Expand All @@ -144,72 +171,73 @@ public function authenticate(Request $request): Passport
throw new AuthenticationServiceException('loadUserByOAuthUserResponse() must return a UserInterface.');
}

$this->rawToken = $token->getRawToken();
$this->resourceOwnerName = $resourceOwner->getName();
$this->refreshToken = $token->getRefreshToken();
$this->createdAt = $token->getCreatedAt();

return new SelfValidatingPassport(
class_exists(UserBadge::class)
? new UserBadge(
method_exists($user, 'getUserIdentifier') ? $user->getUserIdentifier() : $user->getUsername(),
static function () use ($user) { return $user; }
)
: $user
);
return $this->recreateToken($token, $user);
}

/**
* @param Passport|SelfValidatingPassport $passport
* @template T of OAuthToken
*
* @param T $token
* @param ?UserInterface $user
*
* @return T
*/
public function createAuthenticatedToken($passport, string $firewallName): TokenInterface
public function recreateToken(OAuthToken $token, ?UserInterface $user = null): OAuthToken
{
$token = $this->createToken($passport, $firewallName);
$user = $user instanceof UserInterface ? $user : $token->getUser();

$tokenKlass = \get_class($token);
if ($user) {
$newToken = new $tokenKlass(
$token->getRawToken(),
method_exists($user, 'getRoles') ? $user->getRoles() : []
);
$newToken->setUser($user);
} else {
$newToken = new $tokenKlass($token->getRawToken());
}

$this->rawToken = null;
$this->resourceOwnerName = null;
$this->refreshToken = null;
$this->createdAt = null;
$newToken->setResourceOwnerName($token->getResourceOwnerName());
$newToken->setRefreshToken($token->getRefreshToken());
$newToken->setCreatedAt($token->getCreatedAt());
$newToken->setTokenSecret($token->getTokenSecret());
$newToken->setAttributes($token->getAttributes());

return $token;
}
// @deprecated since Symfony 5.4
if (method_exists($newToken, 'setAuthenticated')) {
$newToken->setAuthenticated((bool) $user, false);
}

public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
return $this->successHandler->onAuthenticationSuccess($request, $token);
$token->copyPersistentDataTo($newToken);

return $newToken;
}

public function onAuthenticationFailure(Request $request, AuthenticationException $exception): Response
public function createToken(Passport $passport, string $firewallName): TokenInterface
{
return $this->failureHandler->onAuthenticationFailure($request, $exception);
return $this->createAuthenticatedToken($passport, $firewallName);
}

public function createToken(Passport $passport, string $firewallName): TokenInterface
/**
* @param Passport|SelfValidatedOAuthPassport $passport
*/
public function createAuthenticatedToken($passport, string $firewallName): TokenInterface
{
$token = new OAuthToken($this->rawToken, $passport->getUser()->getRoles());
$token->setResourceOwnerName($this->resourceOwnerName);
$token->setUser($passport->getUser());
$token->setRefreshToken($this->refreshToken);
$token->setCreatedAt($this->createdAt);

// required for compatibility with Symfony 5.4
if (method_exists($token, 'setAuthenticated')) {
$token->setAuthenticated(true, false);
if ($passport instanceof SelfValidatedOAuthPassport) {
return $passport->getToken();
}

return $token;
throw new \LogicException(sprintf('The first argument of "%s" must be instance of "%s", "%s" provided.', __METHOD__, SelfValidatedOAuthPassport::class, \get_class($passport)));
}

private function refreshToken(OAuthToken $expiredToken, ResourceOwnerInterface $resourceOwner): OAuthToken
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
if (!$expiredToken->getRefreshToken()) {
return $expiredToken;
}

$token = new OAuthToken($resourceOwner->refreshAccessToken($expiredToken->getRefreshToken()));
$token->setRefreshToken($expiredToken->getRefreshToken());
return $this->successHandler->onAuthenticationSuccess($request, $token);
}

return $token;
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): Response
{
return $this->failureHandler->onAuthenticationFailure($request, $exception);
}

private function extractCsrfTokenFromState(?string $stateParameter): ?string
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

/*
* This file is part of the HWIOAuthBundle package.
*
* (c) Hardware Info <opensource@hardware.info>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace HWI\Bundle\OAuthBundle\Security\Http\Authenticator\Passport;

use HWI\Bundle\OAuthBundle\Security\Core\Authentication\Token\OAuthToken;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\BadgeInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;

/**
* SelfValidatingPassport contained OAuthToken.
*/
class SelfValidatedOAuthPassport extends SelfValidatingPassport
{
private OAuthToken $token;

/**
* Token already contains authenticated user. No need to create trivial UserBadge outside.
*
* @param BadgeInterface[] $badges
*/
public function __construct(OAuthToken $token, array $badges = [])
{
$this->token = $token;

$user = $token->getUser();

$userBadge = class_exists(UserBadge::class)
? new UserBadge(
method_exists($user, 'getUserIdentifier') ? $user->getUserIdentifier() : $user->getUsername(),
static function () use ($user) { return $user; }
)
: $user;

parent::__construct($userBadge, $badges);
}

public function getToken(): OAuthToken
{
return $this->token;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public function testAuthenticate(): void
->willReturn(true);

$serviceLocator = $this->createMock(ServiceLocator::class);
$serviceLocator->expects($this->once())
$serviceLocator->expects($this->exactly(2))
->method('get')
->with($resourceOwnerName)
->willReturn($resourceOwnerMock);
Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@

"scripts": {
"csfixer": "vendor/bin/php-cs-fixer fix --verbose --dry-run",
"csfixer-diff": "vendor/bin/php-cs-fixer fix --verbose --dry-run --diff",
"csfixer-fix": "vendor/bin/php-cs-fixer fix --verbose",
"phpunit": "vendor/bin/phpunit",
"phpstan": "vendor/bin/phpstan"
Expand Down

0 comments on commit 122c67d

Please sign in to comment.