- Generate keys.
- Install package via composer:
composer require atlance/jwt-auth ^7.0
. - Configure:
- Copy/paste configuration to
config/packages/atlance_jwt_auth.yaml
. - Copy/paste environments to your
.env
and configure.
- Copy/paste configuration to
- Implemened:
Atlance\JwtAuth\Security\UseCase\Create\Token\Handler
. - Example:
<?php
declare(strict_types=1);
namespace App\Controller\Login;
use Atlance\JwtAuth\Security\UseCase;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
use Symfony\Component\Security\Core\User\UserProviderInterface;
#[Route('/login', methods: ['POST'])]
final class Controller extends AbstractController
{
public function __invoke(
Request $request,
UserProviderInterface $provider,
UserPasswordHasherInterface $hasher,
UseCase\Create\Token\HandlerInterface $handler,
): JsonResponse {
/** @var array{username:string,password:string} $dataset */
$dataset = json_decode($request->getContent(), true);
try {
$user = $provider->loadUserByIdentifier($dataset['username']);
$hasher->isPasswordValid($user, $hasher->hashPassword($user, $dataset['password']));
return new JsonResponse(['token' => $handler->handle($user)]);
} catch (UserNotFoundException) {
return new JsonResponse(status: Response::HTTP_BAD_REQUEST);
}
}
}
Implemened:
Atlance\JwtAuth\Security\UseCase\Access\Token\Handler
Atlance\JwtAuth\Security\Factory\UserBadgeFactory
# config/packages/security.yaml
security:
firewalls:
main:
access_token:
token_handler: Atlance\JwtAuth\Security\Factory\UserBadgeFactory
- And Symfony automatically used JWT for authentication.
- More: How to use Access Token Authentication.
- Example:
<?php
declare(strict_types=1);
namespace App\Controller\Profile;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Http\Attribute\CurrentUser;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted('ROLE_USER')]
#[Route('/profile', methods: ['GET'])]
class ProfileController extends AbstractController
{
public function __invoke(#[CurrentUser] ?UserInterface $user = null): JsonResponse
{
return new JsonResponse(['username' => $user->getUserIdentifier()]);
}
}