fix: send cookie after authentication

This commit is contained in:
Maël Gangloff
2024-08-05 19:03:47 +02:00
parent 3341ba00c7
commit 4e6649fc68
3 changed files with 19 additions and 15 deletions

View File

@@ -2,7 +2,7 @@ lexik_jwt_authentication:
secret_key: '%env(resolve:JWT_SECRET_KEY)%'
public_key: '%env(resolve:JWT_PUBLIC_KEY)%'
pass_phrase: '%env(JWT_PASSPHRASE)%'
token_ttl: 3600 # in seconds, default is 3600
token_ttl: 7200 # in seconds, default is 3600
token_extractors:
authorization_header:
enabled: true

View File

@@ -7,6 +7,7 @@ use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Events;
use Lexik\Bundle\JWTAuthenticationBundle\Response\JWTAuthenticationSuccessResponse;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
@@ -15,13 +16,11 @@ use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
readonly class JWTAuthenticator implements AuthenticationSuccessHandlerInterface
class JWTAuthenticator implements AuthenticationSuccessHandlerInterface
{
public function __construct(
private JWTTokenManagerInterface $jwtManager,
private EventDispatcherInterface $dispatcher,
private iterable $cookieProviders = [],
private bool $removeTokenFromBodyWhenCookiesUsed = true
protected JWTTokenManagerInterface $jwtManager,
protected EventDispatcherInterface $dispatcher,
) {
}
@@ -40,10 +39,19 @@ readonly class JWTAuthenticator implements AuthenticationSuccessHandlerInterface
$jwt = $this->jwtManager->create($user);
}
$jwtCookies = [];
foreach ($this->cookieProviders as $cookieProvider) {
$jwtCookies[] = $cookieProvider->createCookie($jwt);
}
$jwtCookies = [
new Cookie(
'BEARER',
$jwt,
time() + 7200, // expiration
'/',
null,
true,
true,
false,
'strict'
),
];
$response = new JWTAuthenticationSuccessResponse($jwt, [], $jwtCookies);
$event = new AuthenticationSuccessEvent(['token' => $jwt], $user, $response);
@@ -51,10 +59,6 @@ readonly class JWTAuthenticator implements AuthenticationSuccessHandlerInterface
$this->dispatcher->dispatch($event, Events::AUTHENTICATION_SUCCESS);
$responseData = $event->getData();
if ($jwtCookies && $this->removeTokenFromBodyWhenCookiesUsed) {
unset($responseData['token']);
}
if ($responseData) {
$response->setData($responseData);
} else {

View File

@@ -75,7 +75,7 @@ class OAuthAuthenticator extends OAuth2Authenticator implements AuthenticationEn
new Cookie(
'BEARER',
$token,
time() + 3600, // expiration
time() + 7200, // expiration
'/',
null,
true,