feat: issue JWT cookie when OAuth

This commit is contained in:
Maël Gangloff
2024-07-23 13:31:45 +02:00
parent 0e82229121
commit fa11235270
2 changed files with 23 additions and 16 deletions

View File

@@ -3,13 +3,9 @@
namespace App\Controller;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Http\Attribute\IsGranted;
class HomeController extends AbstractController
{
@@ -25,11 +21,4 @@ class HomeController extends AbstractController
{
return $clientRegistry->getClient('oauth')->redirect();
}
#[Route(path: "/login/oauth/token", name: "oauth_connect_token")]
#[IsGranted('IS_AUTHENTICATED_FULLY')]
public function loginOAuthToken(UserInterface $user, JWTTokenManagerInterface $JWTManager): JsonResponse
{
return new JsonResponse(['token' => $JWTManager->create($user)]);
}
}

View File

@@ -7,6 +7,8 @@ use App\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use KnpU\OAuth2ClientBundle\Security\Authenticator\OAuth2Authenticator;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
@@ -22,10 +24,11 @@ class OAuthAuthenticator extends OAuth2Authenticator implements AuthenticationEn
{
public function __construct(
private readonly ClientRegistry $clientRegistry,
private readonly UserRepository $userRepository,
private readonly EntityManagerInterface $em,
private readonly RouterInterface $router
private readonly ClientRegistry $clientRegistry,
private readonly UserRepository $userRepository,
private readonly EntityManagerInterface $em,
private readonly RouterInterface $router,
private readonly JWTTokenManagerInterface $JWTManager
)
{
}
@@ -67,7 +70,22 @@ class OAuthAuthenticator extends OAuth2Authenticator implements AuthenticationEn
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): RedirectResponse
{
return new RedirectResponse($this->router->generate('index'));
$token = $this->JWTManager->create($token->getUser());
$response = new RedirectResponse($this->router->generate('index'));
$response->headers->setCookie(
new Cookie(
'BEARER',
$token,
time() + 3600, // expiration
'/',
null,
true,
true,
false,
'strict'
)
);
return $response;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response