atlance/jwt-auth
Composer 安装命令:
composer require atlance/jwt-auth
包简介
Symfony JWT Authentication
README 文档
README
Installation
- 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
.envand configure.
- Copy/paste configuration to
Use Case
Create:
- 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); } } }
Access:
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
- 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()]); } }
Resources
统计信息
- 总下载量: 9
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 1
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2023-05-15