Files
php-qml/framework/php/src/SessionAuthenticator.php

73 lines
2.5 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
namespace PhpQml\Bridge;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
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;
/**
* Validates the per-session bearer token shared between the Qt host
* and the Symfony backend.
*
* In dev mode the token is read from `.env.local`; in bundled mode the
* Qt host generates it per session and passes it to FrankenPHP via env.
* See PLAN.md §3 (*Run modes*, *Edge cases Per-session secret rotation*).
*/
final class SessionAuthenticator extends AbstractAuthenticator
{
public function __construct(
#[\SensitiveParameter]
private readonly string $expectedToken,
) {
}
public function supports(Request $request): bool
{
return $request->headers->has('Authorization');
}
public function authenticate(Request $request): Passport
{
$header = (string) $request->headers->get('Authorization', '');
if (!str_starts_with($header, 'Bearer ')) {
throw new AuthenticationException('Bearer token missing.');
}
$token = substr($header, 7);
if ('' === $this->expectedToken || !hash_equals($this->expectedToken, $token)) {
throw new AuthenticationException('Bearer token invalid.');
}
// Single-session model — there is one bridge "user", not per-end-user auth.
return new SelfValidatingPassport(new UserBadge('bridge'));
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
return null;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): Response
{
return new JsonResponse(
[
'type' => 'about:blank',
'title' => 'Unauthorized',
'status' => Response::HTTP_UNAUTHORIZED,
'detail' => $exception->getMessage(),
],
Response::HTTP_UNAUTHORIZED,
['Content-Type' => 'application/problem+json'],
);
}
}