Skip to content
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

Support authentication manager #685

Open
wants to merge 18 commits into
base: master
Choose a base branch
from
Open
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
17 changes: 7 additions & 10 deletions .github/workflows/continuous-integration.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ jobs:
php-version: '7.4'
coverage: 'none'
extensions: 'json, mbstring, tokenizer'
tools: 'composer-normalize, php-cs-fixer:2.16.4'
tools: 'composer-normalize, php-cs-fixer:3.10.0'
env:
update: true

Expand All @@ -24,7 +24,7 @@ jobs:
php-cs-fixer --version

- name: 'Check PHP code'
run: 'php-cs-fixer fix --diff --dry-run --using-cache=false'
run: 'php-cs-fixer fix --diff --dry-run --using-cache=no --config=.php-cs-fixer.dist-php'

- name: 'Check composer.json'
run: 'composer-normalize --diff --dry-run --no-update-lock'
Expand Down Expand Up @@ -58,17 +58,14 @@ jobs:
name: 'Unit Tests'
strategy:
matrix:
php:
- '7.2'
- '7.3'
- '7.4'
- '8.0'
dependencies:
- 'lowest'
- 'highest'
- 'beta'
include:
- dependencies: 'beta'
symfony_version:
- 5.3
- 5.4
env:
SYMFONY_VERSION: '${{ matrix.symfony_version }}'
steps:
Expand All @@ -78,7 +75,7 @@ jobs:
- name: 'Setup PHP'
uses: 'shivammathur/setup-php@v2'
with:
php-version: '${{ matrix.php }}'
php-version: '7.4'
coverage: 'none'
tools: 'composer:2'
extensions: 'mongodb'
Expand All @@ -90,7 +87,7 @@ jobs:
- run: |
if [ "${{ matrix.dependencies }}" = "beta" ]; then make composer-config-beta; fi;

- run: 'composer rem symfony/form -n --no-update && composer req "symfony/form: ^4.4 || ^5.1" doctrine/annotations --no-update -n'
- run: 'composer rem symfony/form -n --no-update && composer req "symfony/form: ^5.3 || ^6.0" doctrine/annotations --no-update -n'

- uses: 'ramsey/composer-install@v2'
with:
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ Propel/map/
composer.lock
.php_cs.cache
.phpunit.result.cache
.php-cs-fixer.php
15 changes: 8 additions & 7 deletions .php_cs.dist → .php-cs-fixer.dist-php
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
EOF;

$finder = PhpCsFixer\Finder::create()
$finder = (new PhpCsFixer\Finder())
->exclude('vendor')
->in(__DIR__);

return PhpCsFixer\Config::create()
return (new PhpCsFixer\Config())
->setRiskyAllowed(true)
->setUsingCache(false)
->setRules(
Expand All @@ -33,16 +33,16 @@ return PhpCsFixer\Config::create()
'combine_consecutive_unsets' => true,
'declare_strict_types' => true,
'dir_constant' => true,
'general_phpdoc_annotation_remove' => ['@author'],
'echo_tag_syntax' => ['format' => 'long'],
'general_phpdoc_annotation_remove' => ['annotations' => ['@author']],
'header_comment' => ['header' => $header],
'linebreak_after_opening_tag' => true,
'mb_str_functions' => true,
'modernize_types_casting' => true,
// 'native_function_invocation' => true,
'no_extra_consecutive_blank_lines' => ['continue', 'extra', 'return', 'throw', 'use', 'parenthesis_brace_block', 'square_brace_block', 'curly_brace_block'],
'multiline_whitespace_before_semicolons' => ['strategy' => 'new_line_for_chained_calls'],
'no_extra_blank_lines' => ['tokens' => ['continue', 'extra', 'return', 'throw', 'use', 'parenthesis_brace_block', 'square_brace_block', 'curly_brace_block']],
'no_php4_constructor' => true,
'no_short_echo_tag' => true,
'no_unreachable_default_argument_value' => true,
'no_useless_else' => true,
'no_useless_return' => true,
Expand All @@ -54,11 +54,12 @@ return PhpCsFixer\Config::create()
'php_unit_strict' => true,
'phpdoc_add_missing_param_annotation' => true,
'phpdoc_annotation_without_dot' => true,
'phpdoc_inline_tag' => false,
'phpdoc_no_empty_return' => false,
'phpdoc_order' => true,
// phpdoc tag defaults are annotation
// see https://cs.symfony.com/doc/rules/phpdoc/phpdoc_tag_type.html
// 'phpdoc_tag_type' => [],
'phpdoc_to_comment' => false,
'psr4' => true,
'random_api_migration' => true,
'semicolon_after_instruction' => true,
'single_import_per_statement' => true,
Expand Down
2 changes: 1 addition & 1 deletion DependencyInjection/FOSOAuthServerExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public function load(array $configs, ContainerBuilder $container)
} else {
$container->setAlias('fos_oauth_server.document_manager', new Alias(
sprintf('doctrine.odm.%s_mongodb.document_manager',
$config['model_manager_name']),
$config['model_manager_name']),
false
));
}
Expand Down
19 changes: 18 additions & 1 deletion DependencyInjection/Security/Factory/OAuthFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

namespace FOS\OAuthServerBundle\DependencyInjection\Security\Factory;

use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\AuthenticatorFactoryInterface;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SecurityFactoryInterface;
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Component\DependencyInjection\ChildDefinition;
Expand All @@ -24,8 +25,24 @@
*
* @author Arnaud Le Blanc <[email protected]>
*/
class OAuthFactory implements SecurityFactoryInterface
class OAuthFactory implements AuthenticatorFactoryInterface, SecurityFactoryInterface
{
/**
* {@inheritdoc}
*/
public function createAuthenticator(ContainerBuilder $container, string $id, array $config, string $userProviderId)
{
$providerId = 'fos_oauth_server.security.authentication.authenticator.'.$id;
$container
->setDefinition($providerId, new ChildDefinition('fos_oauth_server.security.authentication.authenticator'))
->replaceArgument(0, new Reference('fos_oauth_server.server'))
->replaceArgument(1, new Reference('security.user_checker.'.$id))
->replaceArgument(2, new Reference($userProviderId))
;

return $providerId;
}

/**
* {@inheritdoc}
*/
Expand Down
15 changes: 13 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,29 @@ cs:
sh -c "${QA_DOCKER_COMMAND} php-cs-fixer fix -vvv --diff"

cs-full:
sh -c "${QA_DOCKER_COMMAND} php-cs-fixer fix -vvv --using-cache=false --diff"
if [ ! -f .php-cs-fixer.php ]; then cp .php-cs-fixer.dist-php .php-cs-fixer.php; fi
sh -c "${QA_DOCKER_COMMAND} php-cs-fixer fix -vvv --using-cache=no --diff"

cs-full-check:
sh -c "${QA_DOCKER_COMMAND} php-cs-fixer fix -vvv --using-cache=false --diff --dry-run"
if [ ! -f .php-cs-fixer.php ]; then cp .php-cs-fixer.dist-php .php-cs-fixer.php; fi
sh -c "${QA_DOCKER_COMMAND} php-cs-fixer fix -vvv --using-cache=no --diff --dry-run"

composer-compat:
composer config "platform.ext-mongo" "1.6.16"
composer config --no-plugins allow-plugins.symfony/runtime true
composer require alcaeus/mongo-php-adapter --no-update

composer-config-beta:
composer config "minimum-stability" "beta"

composer-php7:
# when php 7 and 8 are both installed, to test with php7 - for example:
# $ make composer-compat
# $ make composer-php7
# $ SYMFONY_VERSION=5.3 make composer-install
# $ php7.4 vendor/bin/phpunit
composer config platform.php 7.4

composer-install:
rm -f composer.lock && cp composer.json composer.json~
ifdef SYMFONY_VERSION
Expand Down
7 changes: 7 additions & 0 deletions Resources/config/security.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,19 @@
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

<parameters>
<parameter key="fos_oauth_server.security.authentication.authenticator.class">FOS\OAuthServerBundle\Security\Authentication\Authenticator\OAuthAuthenticator</parameter>
<parameter key="fos_oauth_server.security.authentication.provider.class">FOS\OAuthServerBundle\Security\Authentication\Provider\OAuthProvider</parameter>
<parameter key="fos_oauth_server.security.authentication.listener.class">FOS\OAuthServerBundle\Security\Firewall\OAuthListener</parameter>
<parameter key="fos_oauth_server.security.entry_point.class">FOS\OAuthServerBundle\Security\EntryPoint\OAuthEntryPoint</parameter>
</parameters>

<services>
<service id="fos_oauth_server.security.authentication.authenticator" class="%fos_oauth_server.security.authentication.authenticator.class%" public="false">
<argument type="service" id="fos_oauth_server.server" />
<argument type="service" id="security.user_checker" />
<argument /> <!-- user provider -->
</service>

<service id="fos_oauth_server.security.authentication.provider" class="%fos_oauth_server.security.authentication.provider.class%" public="false">
<argument /> <!-- user provider -->
<argument type="service" id="fos_oauth_server.server" />
Expand Down
181 changes: 181 additions & 0 deletions Security/Authentication/Authenticator/OAuthAuthenticator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
<?php

declare(strict_types=1);

/*
* This file is part of the FOSOAuthServerBundle package.
*
* (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace FOS\OAuthServerBundle\Security\Authentication\Authenticator;

use FOS\OAuthServerBundle\Security\Authentication\Passport\OAuthCredentials;
use FOS\OAuthServerBundle\Security\Authentication\Token\OAuthToken;
use OAuth2\OAuth2;
use OAuth2\OAuth2AuthenticateException;
use OAuth2\OAuth2ServerException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AccountStatusException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
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\PassportInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\UserPassportInterface;

/**
* OAuthAuthenticator class.
*
* @author Israel J. Carberry <[email protected]>
*/
class OAuthAuthenticator implements AuthenticatorInterface
{
/**
* @var OAuth2
*/
protected $serverService;

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

/**
* @var UserProviderInterface
*/
protected $userProvider;

public function __construct(
OAuth2 $serverService,
UserCheckerInterface $userChecker,
UserProviderInterface $userProvider
) {
$this->serverService = $serverService;
$this->userChecker = $userChecker;
$this->userProvider = $userProvider;
}

/**
* {@inheritdoc}
*/
public function authenticate(Request $request): UserPassportInterface
{
// remove the authorization header from the request on this check
$tokenString = $this->serverService->getBearerToken($request, true);
$accessToken = $scope = $user = $username = null;

try {
$accessToken = $this->serverService->verifyAccessToken($tokenString);
$scope = $accessToken->getScope();
$user = $accessToken->getUser();
// allow for dependency on deprecated getUsername method
$username = $user instanceof UserInterface
? (method_exists($user, 'getUserIdentifier') ? $user->getUserIdentifier() : $user->getUsername())
: null
;
} catch (OAuth2AuthenticateException $e) {
// do nothing - credentials will remain unresolved below
}

// configure the passport badges, ensuring requisite string types
$userBadge = new UserBadge($username ?? '');
$credentials = new OAuthCredentials($tokenString ?? '', $scope ?? '');

// check the user if not null
if ($user instanceof UserInterface) {
try {
$this->userChecker->checkPreAuth($user);

// mark the credentials as resolved
$credentials->markResolved();
} catch (AccountStatusException $e) {
// do nothing - credentials remain unresolved
}
}

// passport will only be valid if all badges are resolved (user badge
// is always resolved, credentials badge if passing the above check)
return new Passport($userBadge, $credentials);
}

/**
* {@inheritdoc}
*/
public function createAuthenticatedToken(PassportInterface $passport, string $firewallName): TokenInterface
{
try {
// expect the badges in the passport from authenticate method above
if (!$passport->hasBadge(OAuthCredentials::class)
|| !$passport->hasBadge(UserBadge::class)
) {
throw new OAuth2AuthenticateException((string) Response::HTTP_UNAUTHORIZED, OAuth2::TOKEN_TYPE_BEARER, $this->serverService->getVariable(OAuth2::CONFIG_WWW_REALM), 'access_denied', 'Unexpected credentials type.');
}

// get the passport badges
$credentials = $passport->getBadge(OAuthCredentials::class);
$user = $this->userProvider->loadUserByIdentifier(
$passport->getBadge(UserBadge::class)->getUserIdentifier()
);

// check the user
try {
$this->userChecker->checkPostAuth($user);
} catch (AccountStatusException $e) {
throw new OAuth2AuthenticateException((string) Response::HTTP_UNAUTHORIZED, OAuth2::TOKEN_TYPE_BEARER, $this->serverService->getVariable(OAuth2::CONFIG_WWW_REALM), 'access_denied', $e->getMessage());
}
} catch (OAuth2ServerException $e) {
throw new AuthenticationException('OAuth2 authentication failed', 0, $e);
}

$token = new OAuthToken($credentials->getRoles($user));
$token->setAuthenticated(true);
$token->setToken($credentials->getTokenString());
$token->setUser($user);

return $token;
}

/**
* {@inheritdoc}
*/
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
return null;
}

/**
* {@inheritdoc}
*/
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
$responseException = new OAuth2AuthenticateException(
(string) Response::HTTP_UNAUTHORIZED,
OAuth2::TOKEN_TYPE_BEARER,
$this->serverService->getVariable(OAuth2::CONFIG_WWW_REALM),
'access_denied',
$exception->getMessage()
);

return $responseException->getHttpResponse();
}

/**
* {@inheritdoc}
*/
public function supports(Request $request): ?bool
{
// do not remove the authorization header from the request on this check
$tokenString = $this->serverService->getBearerToken($request);

return is_string($tokenString) && !empty($tokenString);
}
}
Loading