I used lexik/jwt-authentication-bundle.
security.yaml
security:
encoders:
# an encoder used in the past for some users
legacy:
algorithm: sha256
encode_as_base64: false
iterations: 1
App\Entity\User:
# the new encoder, along with its options
algorithm: auto
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
providers:
# used to reload user from session & other features (e.g. switch_user)
app_user_provider:
entity:
class: App\Entity\User
property: email
# used to reload user from session & other features (e.g. switch_user)
# used to reload user from session & other features (e.g. switch_user)
firewalls:
login:
pattern: ^/api/users/login
stateless: true
anonymous: true
provider: app_user_provider
json_login:
check_path: api_login
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
register:
pattern: ^/api/users/register
stateless: true
anonymous: true
provider: app_user_provider
json_login:
check_path: api_register
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
api:
pattern: ^/api
stateless: true
anonymous: false
provider: app_user_provider
guard:
authenticators:
- lexik_jwt_authentication.jwt_token_authenticator
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
access_control:
- { path: ^/api/users/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/api/users/register, roles: IS_AUTHENTICATED_ANONYMOUSLY }
lexik_jwt_authentication.yaml
lexik_jwt_authentication:
secret_key: '%kernel.project_dir%/config/jwt/private.pem'
public_key: '%kernel.project_dir%/config/jwt/public.pem'
pass_phrase: '%env(JWT_PASSPHRASE)%' # If using public/private key pair (optional)
token_ttl: 3600 # Token Time-to-live (in seconds)
UserController.php
/**
* @Route("/api/users/login", name="app_user_login", methods="POST")
*/
public function login(Request $request): Response
{
$email = $request->request->get('email');
$password = $request->request->get('password');
$user = $this->getDoctrine()->getRepository(User::class)->findOneBy(['email' => $email]);
if (!$user) {
return $this->json(['message' => 'Invalid credentials'], 401);
} else if (!$this->userPasswordEncoder->isPasswordValid($user, $password)) {
return $this->json(['success' => false, 'msg' => 'Password Incorrect!']);
}
// Generate the JWT token
$token = $this->jwtTokenManager->create($user);
return $this->json([
'token' => $token,
]);
}
Test by Postman, and result is:
JWTEncodeFailureException
Unable to create a signed JWT from the given configuration.
How can I solve it?