How to create jwt token in symfony 5?

Member

by ryleigh , in category: PHP Frameworks , a month ago

How to create jwt token in symfony 5?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by mallory_cormier , a month ago

@ryleigh 

To create a JWT token in Symfony 5, you can use the LexikJWTAuthenticationBundle which provides tools for handling JWT tokens in Symfony applications. Here is a step-by-step guide on how to create a JWT token in Symfony 5 using the LexikJWTAuthenticationBundle:

  1. Install the LexikJWTAuthenticationBundle using Composer:
1
composer require lexik/jwt-authentication-bundle


  1. Enable the bundle in your config/bundles.php file:
1
2
3
4
return [
    // ...
    LexikBundleJWTAuthenticationBundleLexikJWTAuthenticationBundle::class => ['all' => true],
];


  1. Configure the bundle in your config/packages/lexik_jwt_authentication.yaml file:
1
2
3
4
5
6
lexik_jwt_authentication:
    secret_key: '%env(APP_SECRET)%' # Your secret key
    public_key: '%env(PUBLIC_KEY_PATH)%' # Path to the public key
    private_key: '%env(PRIVATE_KEY_PATH)%' # Path to the private key
    pass_phrase: '%env(JWT_PASSPHRASE)%' # Passphrase for the private key
    token_ttl: 3600 # Token expiration time


  1. Generate the public and private keys (if you don't already have them): You can generate the keys using the following OpenSSL commands:
1
2
3
4
5
# Generate a private key
openssl genrsa -out config/jwt/private.pem 4096

# Create the public key
openssl rsa -pubout -in config/jwt/private.pem -out config/jwt/public.pem


  1. Create a controller action to generate the JWT token:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
use LexikBundleJWTAuthenticationBundleServicesJWTTokenManagerInterface;

public function getToken(JWTTokenManagerInterface $jwtManager)
{
    $user = $this->getUser(); // Get the authenticated user

    $token = $jwtManager->create($user);

    return new JsonResponse(['token' => $token]);
}


  1. You can now call the getToken action to generate a JWT token for the authenticated user.


Please note that this is a basic example of generating a JWT token in Symfony 5. You may need to additional configurations and validations based on your application requirements.