Convert Figma logo to code with AI

tymondesigns logojwt-auth

🔐 JSON Web Token Authentication for Laravel & Lumen

11,274
1,543
11,274
606

Top Related Projects

9,353

PHP package for JWT

7,251

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

JWT authentication for your Symfony API

Associate users with roles and permissions

2,730

Laravel Sanctum provides a featherweight authentication system for SPAs and simple APIs.

Quick Overview

jwt-auth is a JSON Web Token (JWT) authentication package for Laravel. It provides a simple and secure way to implement token-based authentication in Laravel applications, allowing developers to easily protect routes and manage user authentication using JWTs.

Pros

  • Easy integration with Laravel applications
  • Supports multiple user authentication models
  • Customizable token generation and validation
  • Includes built-in middleware for protecting routes

Cons

  • Limited to Laravel framework
  • Requires understanding of JWT concepts
  • May require additional configuration for complex authentication scenarios
  • Potential security risks if not implemented correctly

Code Examples

  1. Creating a token:
$token = JWTAuth::attempt($credentials);

This code attempts to authenticate a user with the provided credentials and returns a JWT if successful.

  1. Authenticating a user with a token:
$user = JWTAuth::parseToken()->authenticate();

This code parses the token from the request and authenticates the user, returning the user object.

  1. Refreshing a token:
$newToken = JWTAuth::refresh(JWTAuth::getToken());

This code refreshes an existing token, extending its validity period.

Getting Started

  1. Install the package via Composer:
composer require tymon/jwt-auth
  1. Publish the config file:
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
  1. Generate a secret key:
php artisan jwt:secret
  1. Configure your config/auth.php file:
'guards' => [
    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],
  1. Implement the JWTSubject interface in your User model:
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    public function getJWTCustomClaims()
    {
        return [];
    }
}
  1. Add middleware to your routes:
Route::group(['middleware' => ['jwt.auth']], function() {
    Route::get('user', 'UserController@getAuthenticatedUser');
});

Competitor Comparisons

9,353

PHP package for JWT

Pros of php-jwt

  • Lightweight and simple implementation focused solely on JWT encoding/decoding
  • Easy to integrate into existing PHP projects without framework dependencies
  • Supports various algorithms (HS256, RS256, etc.) for token signing

Cons of php-jwt

  • Lacks built-in features for authentication and authorization
  • Requires manual implementation of token management and validation logic
  • No out-of-the-box integration with popular PHP frameworks

Code Comparison

php-jwt:

use Firebase\JWT\JWT;

$payload = ['user_id' => 123];
$jwt = JWT::encode($payload, $key, 'HS256');
$decoded = JWT::decode($jwt, $key, ['HS256']);

jwt-auth:

use Tymon\JWTAuth\Facades\JWTAuth;

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

Key Differences

  • jwt-auth is a full-featured authentication package for Laravel, while php-jwt is a standalone JWT library
  • jwt-auth provides middleware, automatic token refreshing, and user retrieval, whereas php-jwt focuses on core JWT functionality
  • php-jwt offers more flexibility for use in various PHP projects, while jwt-auth is tailored for Laravel applications

Use Cases

  • Choose php-jwt for simple JWT implementation in non-Laravel PHP projects or when you need low-level control over JWT handling
  • Opt for jwt-auth when building Laravel applications that require a complete JWT authentication solution with minimal setup
7,251

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

Pros of jwt

  • More flexible and customizable, allowing for greater control over JWT handling
  • Supports a wider range of algorithms and claim types
  • Actively maintained with regular updates and improvements

Cons of jwt

  • Steeper learning curve due to its more complex API
  • Requires more manual configuration for integration with frameworks
  • Less opinionated, which may lead to more boilerplate code in some cases

Code Comparison

jwt-auth:

$token = JWTAuth::attempt($credentials);
$user = JWTAuth::toUser($token);

jwt:

$token = $config->builder()
    ->withClaim('uid', $user->id)
    ->getToken($config->signer(), $config->signingKey());
$claims = $config->parser()->parse($token)->claims();

The jwt-auth library provides a more straightforward API for common JWT operations, while jwt offers more granular control over token creation and parsing. jwt-auth is better suited for quick integration with Laravel projects, whereas jwt is more versatile for use in various PHP applications and frameworks.

Both libraries have their strengths, and the choice between them depends on the specific requirements of your project, desired level of control, and integration needs.

JWT authentication for your Symfony API

Pros of LexikJWTAuthenticationBundle

  • Seamless integration with Symfony framework and its security components
  • Supports custom token encoders and user providers
  • Extensive configuration options for token generation and validation

Cons of LexikJWTAuthenticationBundle

  • Limited to Symfony ecosystem, less flexible for other PHP projects
  • Steeper learning curve for developers not familiar with Symfony
  • May require more setup and configuration compared to jwt-auth

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)%'
    token_ttl: 3600

jwt-auth:

'jwt' => [
    'secret' => env('JWT_SECRET'),
    'keys' => [
        'public' => env('JWT_PUBLIC_KEY'),
        'private' => env('JWT_PRIVATE_KEY'),
    ],
    'ttl' => 60,
]

Both libraries offer JWT authentication for PHP applications, but they cater to different ecosystems. LexikJWTAuthenticationBundle is tailored for Symfony projects, providing deep integration with the framework's security components. It offers more extensive configuration options but may be more complex to set up. On the other hand, jwt-auth is more versatile and can be used in various PHP projects, including Laravel. It has a simpler setup process but may lack some of the advanced features found in LexikJWTAuthenticationBundle.

Associate users with roles and permissions

Pros of laravel-permission

  • Focuses on role-based access control (RBAC) for Laravel applications
  • Provides a more granular and flexible permission system
  • Integrates seamlessly with Laravel's built-in authentication system

Cons of laravel-permission

  • Limited to Laravel framework, while jwt-auth can be used with other PHP frameworks
  • Does not handle token-based authentication out of the box
  • May require additional setup for API authentication scenarios

Code Comparison

laravel-permission:

$user->givePermissionTo('edit articles');
$user->assignRole('writer');
$user->hasPermissionTo('edit articles');

jwt-auth:

$token = JWTAuth::attempt($credentials);
$user = JWTAuth::toUser($token);
$payload = JWTAuth::getPayload($token);

Summary

laravel-permission is tailored for managing roles and permissions within Laravel applications, offering fine-grained access control. jwt-auth, on the other hand, focuses on JSON Web Token (JWT) authentication for APIs, which can be used across different PHP frameworks. While laravel-permission excels in RBAC, jwt-auth provides a robust solution for stateless, token-based authentication in API-centric applications.

2,730

Laravel Sanctum provides a featherweight authentication system for SPAs and simple APIs.

Pros of Sanctum

  • Simpler setup and configuration, integrated directly into Laravel
  • Supports both SPA authentication and mobile app tokens
  • Built-in CSRF protection for web routes

Cons of Sanctum

  • Less flexible for complex JWT scenarios
  • Limited customization options for token structure
  • May require additional setup for microservices architecture

Code Comparison

Sanctum token creation:

$token = $user->createToken('token-name')->plainTextToken;

jwt-auth token creation:

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

Additional Considerations

  • jwt-auth offers more granular control over token claims and expiration
  • Sanctum is better suited for Laravel-specific projects
  • jwt-auth may be preferred for cross-platform applications

Both packages provide secure authentication solutions, but Sanctum is more tightly integrated with Laravel's ecosystem, while jwt-auth offers more flexibility for complex JWT implementations. The choice between them depends on specific project requirements and the desired level of customization.

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

jwt-auth-banner

PHPUnit Codecov branch StyleCI Latest Version Latest Dev Version Monthly Downloads

Documentation

jwt-auth.com

jwt-auth versionLaravel version(s)
1.x6 / 7 / 8
2.x9 / 10 / 11


Security

If you discover any security related issues, please email tymon148@gmail.com instead of using the issue tracker.

License

The MIT License (MIT)