composer require atlance/jwt-auth ^7.0.config/packages/atlance_jwt_auth.yaml..env and configure.Atlance\JwtAuth\Security\UseCase\Create\Token\Handler.<?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\HandlerAtlance\JwtAuth\Security\Factory\UserBadgeFactory# config/packages/security.yaml
security:
firewalls:
main:
access_token:
token_handler: Atlance\JwtAuth\Security\Factory\UserBadgeFactory
<?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()]);
}
}
How can I help you explore Laravel packages today?