php-open-source-saver/jwt-auth

repository·main·Indexed 21 days ago

https://github.com/php-open-source-saver/jwt-auth

A JWT (JSON Web Token) authentication library for Laravel, maintained as a fork of tymondesigns/jwt-auth. It provides an API for authenticating users via attempt(), manual login, token refreshing, and invalidation. The library includes Artisan commands for generating secret keys and certificates for asymmetric signing, as well as support for custom claims and configurable TTL per auth guard.

Tokens
14.3K
Snippets
73
Records
77
Agent score
74%

What's inside php-open-source-saver/jwt-auth

  1. Configure custom TTL for Auth Guards

    main

    You can override the global ttl (Time To Live) defined in config/jwt.php by setting a specific ttl value within individual guard configurations in config/auth.php.

    • Custom TTL: Set an integer (e.g., minutes) to define a specific expiration for that guard.
    • No Expiration: Set ttl to null to ensure tokens for that guard never automatically expire.
    • Default TTL: If the ttl key is omitted from the guard configuration, the guard will fall back to the global ttl value defined in config/jwt.php.
    'guards' => [
        'customers' => [
            'driver' => 'jwt',
            'provider' => 'customers',
            'ttl' => env('JWT_CUSTOMERS_TTL', 15), // Custom TTL for 'customers' guard (15 minutes)
        ],
        'administrators' => [
            'driver' => 'jwt',
            'provider' => 'administrators',
            'ttl' => null, // 'administrators' guard has no expiration
        ],
        // if no 'ttl' is set, it will use the 'ttl' value in `config/jwt.php`
        'users' => [
            'driver' => 'jwt',
            'provider' => 'users',
        ],
    ],
  2. Migrate from tymondesigns/jwt-auth to php-open-source-saver/jwt-auth

    main

    This project is a fork of tymondesigns/jwt-auth and uses a different namespace (PHPOpenSourceSaver\JWTAuth instead of Tymon\JWTAuth), but maintains the same features. To migrate, follow these steps:

    1. Remove the old package: composer remove tymon/jwt-auth (you may ignore any errors that appear during this step).
    2. Replace all occurrences of the Tymon\JWTAuth namespace with PHPOpenSourceSaver\JWTAuth in your codebase. You can use your editor's global search and replace feature (e.g., Ctrl + Shift + R).
    3. Install the new package: composer require php-open-source-saver/jwt-auth.

    Compatibility Note: If you have implicitly disabled Laravel package autodiscovery, you may encounter compatibility issues. Specifically, JWTGuard contains a new $eventDispatcher variable in its constructor.

    composer remove tymon/jwt-auth
    # Replace Tymon\JWTAuth with PHPOpenSourceSaver\JWTAuth in your code
    composer require php-open-source-saver/jwt-auth
  3. Implement JWTSubject on your User model

    main

    To use jwt-auth, your User model must implement the PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject contract. This requires implementing two methods:

    1. getJWTIdentifier(): Returns the identifier that will be stored in the sub (subject) claim of the JWT (typically the model's primary key).
    2. getJWTCustomClaims(): Returns an array of custom claims to be added to the JWT payload.
    <?php
    
    namespace App;
    
    use PHPOpenSourceSaverWTAuthWContractsWJWTSubject;
    use Illuminate
    otifications\WNotifiable;
    use IlluminateoundationWAuthWUser as Authenticatable;
    
    class User extends Authenticatable implements JWTSubject
    {
        use Notifiable;
    
        /**
         * Get the identifier that will be stored in the subject claim of the JWT.
         *
         * @return mixed
         */
        public function getJWTIdentifier()
        {
            return $this->getKey();
        }
    
        /**
         * Return a key value array, containing any custom claims to be added to the JWT.
         *
         * @return array
         */
        public function getJWTCustomClaims()
        {
            return [];
        }
    }
  4. Publish the JWT-Auth configuration

    main

    To move the package configuration from the vendor directory to your application's configuration folder, run the following Artisan command:

    php artisan vendor:publish --provider="PHPOpenSourceSaver\JWTAuth\Providers\LaravelServiceProvider"

    After running this, you can customize the package settings in config/jwt.php.

    php artisan vendor:publish --provider="PHPOpenSourceSaver\JWTAuth\Providers\LaravelServiceProvider"
  5. Generate a JWT secret key

    main

    Use the jwt:secret Artisan command to generate a unique secret key used for signing your tokens. Running this command will automatically update your .env file with a JWT_SECRET value (e.g., JWT_SECRET=foobar). The specific way this key is used for signing depends on the algorithm you have configured.

    php artisan jwt:secret
  6. Configure the Auth Guard for JWT

    main

    To enable JWT authentication in Laravel (version 5.2 and above), modify config/auth.php to set the api guard to use the jwt driver and set it as the default guard.

    Update the defaults and guards sections as follows:

    'defaults' => [
        'guard' => 'api',
        'passwords' => 'users',
    ],
    
    ...
    
    'guards' => [
        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
        ],
    ],