我想在我的应用程序中创建JWT。从以下链接开始使用Symfony文档:https://symfony.com/bundles/LexikJWTAuthenticationBundle/current/index.html#about-token-expiration
https://symfony.com/doc/current/security.html#json-login
我找不到任何解决方案。
我的代码如下所示:* * 控制器方法:**
#[Route('api/login', name: 'api_login')]
public function loginUser(Request $request,
JWTTokenManagerInterface $tokenManager
): JsonResponse
{
$credentials = json_decode($request->getContent(), true);
if (!isset($credentials['username'], $credentials['password']) || !$credentials)
{
return new JsonResponse('Missing credentials', Response::HTTP_UNAUTHORIZED);
}
$username = $credentials['username'];
$password = $credentials['password'];
$user = $this->repository->findOneBy(['username' => $username]);
if (!$user instanceof UserInterface || !$this->passwordHasher->isPasswordValid($user, $password))
{
return new JsonResponse('Invalid credentials', Response::HTTP_UNAUTHORIZED);
}
$token = $tokenManager->create($user);
return new JsonResponse($user->getUserIdentifier() . $token);
}
- 路线. yaml**
login:
path: /api/login
- 安全性. yaml**
security:
password_hashers:
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
providers:
app_user_provider:
entity:
class: App\Entity\User
property: username
firewalls:
login:
pattern: ^/api/login
stateless: true
json_login:
check_path: /api/login
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
api:
pattern: ^/api
stateless: true
jwt: ~
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
lazy: true
provider: app_user_provider
access_control:
- { path: ^/api/register, roles: PUBLIC_ACCESS }
- { path: ^/api/login, roles: PUBLIC_ACCESS }
- { path: ^/api, roles: IS_AUTHENTICATED_FULLY }
when@test:
security:
password_hashers:
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface:
algorithm: auto
cost: 4
time_cost: 3
memory_cost: 10
- .环境*
JWT_SECRET_KEY=%kernel.project_dir%/config/jwt/private.pem
JWT_PUBLIC_KEY=%kernel.project_dir%/config/jwt/public.pem
JWT_PASSPHRASE=9c32a9b40d2606c7aed87e3eb8642bd7
- lexik_jwt_身份验证. yaml**
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
- 那是错误**
<!-- Unable to create a signed JWT from the given configuration. (500 Internal Server Error) -->
这就是我得到的全部。有人能从我的网站看到任何错误或可以解决吗?
1条答案
按热度按时间u5rb5r591#
如果您有自定义身份验证工作流,则可以使用custom authenticator。
下面是JWT的一个自定义示例。
然后在
config/services.yaml
中:然后在
.env
中不要忘记在
config/packages/security.yaml
中注册您的验证器: