docker symfony Authenticator Пример авторизации в другом приложении, сервисе,из докера через сеть основной ОС (хостовой системы)
Primary tabs
Можно использовать подобную идею для аутентификатора (в этом примере мы применяем host.docker.internal):
<?php
namespace App\Security;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Core\Authorization\Strategy\UnanimousStrategy;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
class KtuAuthAuthenticator extends AbstractAuthenticator
{
public function supports(Request $request): ?bool
{
return true;
}
public function authenticate(Request $request): Passport
{
$port = 9731; // @TODO перенести в env - подхватить в конфиге
$domain = 'host.docker.internal'; // @TODO перенести в env - подхватить в конфиге
$baseUrl = "http://$domain:$port"; // @TODO сделать инъекцию из конфига, там же можно попробовать собрать эту строчку конкатенацией
$client = new Client([
'base_uri' => $baseUrl,
]);
$sessionCookieName = 'PHPSESSID'; // @TODO сделать инъекцию из env
$authCookieValue = $request->cookies->get($sessionCookieName);
$debugPostfix = '?XDEBUG_SESSION_START=netbeans-xdebug';
$debug = true;
if ($authCookieValue) {
$cookieJar = CookieJar::fromArray([
$sessionCookieName => $authCookieValue
], 'host.docker.internal');
$response = $client->request(
"GET",
"/api/v1/user_info" . ($debug ? $debugPostfix : ''),
[
'http_errors' => false,
'cookies' => $cookieJar
]
);
$userData = json_decode($response->getBody()->getContents());
} else {
throw new UnauthorizedHttpException('No access cookie!');
}
return new SelfValidatingPassport(new UserBadge('testUser', function (string $userIdentifier) use ($userData) {
$User = new User();
$User->setUsername($userData->userIdentifier)
->setRoles($userData->roles);
return $User;
}));
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
// TODO: Implement onAuthenticationSuccess() method.
return null;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
$data = [
// you may want to customize or obfuscate the message first
'message' => strtr($exception->getMessageKey(), $exception->getMessageData())
// or to translate this message
// $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())
];
return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
}
// public function start(Request $request, AuthenticationException $authException = null): Response
// {
// /*
// * If you would like this class to control what happens when an anonymous user accesses a
// * protected page (e.g. redirect to /login), uncomment this method and make this class
// * implement Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface.
// *
// * For more details, see https://symfony.com/doc/current/security...
// */
// }
}
Использовать в config/packages/security.yaml можно так:
security:
# https://symfony.com/doc/current/security...
password_hashers:
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
# https://symfony.com/doc/current/security...
providers:
# used to reload user from session & other features (e.g. switch_user)
app_user_provider:
id: App\Security\UserProvider
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
lazy: true
provider: app_user_provider
custom_authenticators:
- App\Security\KtuAuthAuthenticator
stateless: true- Log in to post comments
- 905 reads