Convert Figma logo to code with AI

lexik logoLexikJWTAuthenticationBundle

JWT authentication for your Symfony API

2,524
610
2,524
110

Top Related Projects

9,397

PHP package for JWT

7,276

A simple library to work with JSON Web Token and JSON Web Signature

11,274

🔐 JSON Web Token Authentication for Laravel & Lumen

Quick Overview

LexikJWTAuthenticationBundle is a Symfony bundle that provides JWT (JSON Web Token) authentication for your Symfony application. It integrates with Symfony's security system to offer a robust and flexible solution for token-based authentication in API-centric projects.

Pros

  • Easy integration with Symfony's security system
  • Supports both symmetric and asymmetric encryption for tokens
  • Customizable token creation and validation process
  • Extensive documentation and active community support

Cons

  • Requires additional setup compared to simpler authentication methods
  • May have a learning curve for developers new to JWT authentication
  • Token revocation requires additional implementation (e.g., blacklisting)
  • Potential security risks if not properly implemented or managed

Code Examples

  1. Configuring JWT authentication in security.yaml:
security:
    firewalls:
        api:
            pattern: ^/api
            stateless: true
            jwt: ~
  1. Generating JWT tokens in a controller:
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;

class AuthController extends AbstractController
{
    public function login(JWTTokenManagerInterface $JWTManager)
    {
        $user = // ... get the user somehow
        $token = $JWTManager->create($user);
        
        return $this->json(['token' => $token]);
    }
}
  1. Accessing the authenticated user in a protected route:
use Symfony\Component\Security\Core\User\UserInterface;

class ApiController extends AbstractController
{
    #[Route('/api/protected', name: 'api_protected')]
    public function protectedAction(UserInterface $user)
    {
        return $this->json([
            'message' => 'Welcome '.$user->getUserIdentifier(),
            'roles' => $user->getRoles(),
        ]);
    }
}

Getting Started

  1. Install the bundle:

    composer require lexik/jwt-authentication-bundle
    
  2. Generate the SSL keys:

    php bin/console lexik:jwt:generate-keypair
    
  3. Configure the bundle in config/packages/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: 'your_secret_passphrase'
        token_ttl: 3600
    
  4. Update your security.yaml to use JWT authentication (see example in Code Examples section).

  5. Create a login route to generate tokens and protect your API routes with the jwt firewall.

Competitor Comparisons

9,397

PHP package for JWT

Pros of php-jwt

  • Lightweight and focused solely on JWT functionality
  • Easy to integrate into any PHP project without framework dependencies
  • Supports a wide range of algorithms for token signing and verification

Cons of php-jwt

  • Lacks built-in Symfony integration and authentication features
  • Requires manual implementation of token handling and user authentication
  • No out-of-the-box support for token refresh or blacklisting

Code Comparison

LexikJWTAuthenticationBundle (Symfony configuration):

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

php-jwt (Token creation):

use Firebase\JWT\JWT;

$payload = [
    'user_id' => 123,
    'exp' => time() + 3600
];
$jwt = JWT::encode($payload, $secretKey, 'HS256');

LexikJWTAuthenticationBundle provides a comprehensive solution for JWT authentication in Symfony applications, offering features like automatic token creation, user provider integration, and event listeners. On the other hand, php-jwt is a more flexible and lightweight library that can be used in any PHP project, but requires manual implementation of authentication logic and token handling.

7,276

A simple library to work with JSON Web Token and JSON Web Signature

Pros of jwt

  • Lightweight and flexible JWT library
  • Language-agnostic, can be used in various PHP projects
  • Supports multiple algorithms and claim validation

Cons of jwt

  • Requires more manual setup for Symfony integration
  • Less opinionated, may need additional configuration for specific use cases
  • Lacks built-in user authentication features

Code Comparison

LexikJWTAuthenticationBundle:

lexik_jwt_authentication:
    secret_key: '%env(resolve:JWT_SECRET_KEY)%'
    public_key: '%env(resolve:JWT_PUBLIC_KEY)%'
    pass_phrase: '%env(JWT_PASSPHRASE)%'

jwt:

use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Signer\Hmac\Sha256;

$config = Configuration::forSymmetricSigner(
    new Sha256(),
    InMemory::base64Encoded('mBC5v1sOKVvbdEitdSBenu59nfNfhwkedkJVNabosTw=')
);

Summary

LexikJWTAuthenticationBundle is a Symfony-specific bundle that provides a complete JWT authentication solution out of the box. It offers easy integration with Symfony's security system and includes user authentication features.

jwt, on the other hand, is a more general-purpose JWT library that can be used in various PHP projects. It provides flexibility and supports multiple algorithms, but requires more manual setup for Symfony integration and lacks built-in user authentication features.

Choose LexikJWTAuthenticationBundle for quick Symfony integration, or jwt for a more flexible, language-agnostic approach to JWT handling in PHP projects.

11,274

🔐 JSON Web Token Authentication for Laravel & Lumen

Pros of jwt-auth

  • Designed specifically for Laravel, offering seamless integration
  • Provides a more extensive set of features out-of-the-box
  • Active community and regular updates

Cons of jwt-auth

  • Limited to Laravel framework, less flexible for other PHP projects
  • May have a steeper learning curve for developers new to Laravel

Code Comparison

LexikJWTAuthenticationBundle:

$token = $this->get('lexik_jwt_authentication.encoder')
    ->encode(['username' => 'user']);

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

jwt-auth:

$token = JWTAuth::fromUser($user);

return response()->json(compact('token'));

Both libraries provide straightforward methods for token generation, but jwt-auth's syntax is more Laravel-centric and concise. LexikJWTAuthenticationBundle offers a more generic approach, suitable for various Symfony-based projects.

While LexikJWTAuthenticationBundle is versatile and works well with Symfony, jwt-auth excels in Laravel environments with its tailored features and integration. The choice between the two depends on the specific framework and project requirements.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

LexikJWTAuthenticationBundle

Latest Stable Version

This bundle provides JWT (Json Web Token) authentication for your Symfony API.

It is compatible (and tested) with PHP > 8.2 and Symfony > 6.4.

Documentation

The bulk of the documentation is stored in the Resources/doc directory of this bundle:

Community Support

Please consider opening a question on StackOverflow using the lexikjwtauthbundle tag, it is the official support platform for this bundle.

Github Issues are dedicated to bug reports and feature requests.

Contributing

See the CONTRIBUTING file.

Sponsoring

Huge thanks to Blackfire and JetBrains for providing this project with free open-source licenses.

Blackfire

If you or your company use this package, please consider sponsoring its maintenance and development.

Upgrading from 1.x

Please see the UPGRADE file.

Credits

License

This bundle is under the MIT license.
For the whole copyright, see the LICENSE file distributed with this source code.