JWT or Json Web Tokens are becoming the standard for Authentication in Http REST Api calls. In Symfony we have the lexik/jwt-authentication-bundle available as a package that allow us to manage jwt in a very easy way.
Step 1. Install the library using Composer:
composer require lexik/jwt-authentication-bundle
Step 2. Configure the bundle in your Symfony application by adding the following lines to your config/bundles.php file:
return [
// ...
Lexik\Bundle\JWTAuthenticationBundle\LexikJWTAuthenticationBundle::class => ['all' => true],
];
Step 3. Configure the JWT authentication in your config/packages/lexik_jwt_authentication.yaml file. Here's an example configuration:
lexik_jwt_authentication:
secret_key: '%env(APP_SECRET)%'
public_key: '%env(JWT_PUBLIC_KEY_PATH)%'
pass_phrase: '%env(JWT_PASSPHRASE)%'
token_ttl: 3600
This configuration defines the secret and public keys for JWT encryption, the passphrase for the private key (if using RSA), and the time-to-live (TTL) for the token.
Step 4. Generate the JWT token in your code:
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
// Inject the JWT token manager service into your controller or service
public function myAction(JWTTokenManagerInterface $jwtManager)
{
// Generate the token for the user
$user = $this->getUser(); // get the user object from your authentication system
$token = $jwtManager->create($user);
// Return the token as a JSON response
return $this->json(['token' => $token]);
}
Read more about this lexik bundle.