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 10, 2021
1 parent 59388c8 commit 679e544
Show file tree
Hide file tree
Showing 5 changed files with 292 additions and 57 deletions.
4 changes: 4 additions & 0 deletions Security/Core/Authentication/Token/AbstractOAuthToken.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,10 @@ public function __unserialize(array $data): void
}
}

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

/**
* @return mixed|void
*/
Expand Down
135 changes: 81 additions & 54 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 @@ -29,9 +30,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 @@ -52,10 +51,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 @@ -144,8 +139,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());
}
$token->copyPersistentDataFrom($expiredToken);
} else {
// if you cannot refresh token, you do not need to make user_info request to oauth-resource
if (null !== $expiredToken->getUser()) {
return $expiredToken;
}
}
unset($expiredToken);
}

$userResponse = $resourceOwner->getUserInformation($token->getRawToken());
Expand All @@ -163,73 +190,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(
// @phpstan-ignore-next-line Symfony <5.4 BC layer
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();

$tokenClass = \get_class($token);
if ($user) {
$newToken = new $tokenClass(
$token->getRawToken(),
method_exists($user, 'getRoles') ? $user->getRoles() : []
);
$newToken->setUser($user);
} else {
$newToken = new $tokenClass($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;
}
// required for compatibility with 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);
}
$newToken->copyPersistentDataFrom($token);

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

public function createToken(Passport $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);
return $this->createAuthenticatedToken($passport, $firewallName);
}

// required for compatibility with Symfony 5.4
if (method_exists($token, 'setAuthenticated')) {
$token->setAuthenticated(true, false);
/**
* @param Passport|SelfValidatedOAuthPassport $passport
*/
public function createAuthenticatedToken($passport, string $firewallName): TokenInterface
{
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;
}
}
16 changes: 14 additions & 2 deletions Tests/Fixtures/CustomOAuthToken.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@

namespace HWI\Bundle\OAuthBundle\Tests\Fixtures;

use HWI\Bundle\OAuthBundle\Security\Core\Authentication\Token\AbstractOAuthToken;
use HWI\Bundle\OAuthBundle\Security\Core\Authentication\Token\OAuthToken;

final class CustomOAuthToken extends OAuthToken
{
public function __construct()
public function __construct(array $accessToken = [])
{
parent::__construct(
[
$accessToken + [
'access_token' => 'access_token_data',
],
[
Expand All @@ -28,4 +29,15 @@ public function __construct()

$this->setUser(new User());
}

public function copyPersistentDataFrom(AbstractOAuthToken $token): void
{
if ($token instanceof self) {
if ($token->hasAttribute('persistent_key')) {
$this->setAttribute('persistent_key', $token->getAttribute('persistent_key'));
}
}

parent::copyPersistentDataFrom($token);
}
}

0 comments on commit 679e544

Please sign in to comment.