jwt-auth (JSON Web Token Authentication for Laravel)

repository·2.x·Indexed 11 days ago

https://github.com/tymondesigns/jwt-auth

A Laravel package providing JSON Web Token (JWT) authentication for building secure, stateless APIs. It includes features for issuing tokens, managing authentication guards, token refreshing, and a blacklist system to invalidate tokens.

Tokens
9.3K
Snippets
57
Records
61
Agent score
94%

What's inside jwt-auth

  1. Overview of jwt-auth

    2.x
    The tymon/jwt-auth package provides JSON Web Token (JWT) authentication for Laravel applications. It allows you to issue tokens to users and use those tokens to authenticate subsequent requests, making it ideal for building stateless APIs.
  2. Configure the JWT Auth guard

    2.x

    In Laravel 5.2 and above, you must configure the api guard to use the jwt driver in your config/auth.php file. This allows you to use Laravel's built-in Auth system while jwt-auth handles the token logic behind the scenes.

    'defaults' => [
        'guard' => 'api',
        'passwords' => 'users',
    ],
    
    ...
    
    'guards' => [
        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
        ],
    ],
  3. Send JWT in authenticated requests

    2.x

    Once a user has logged in and received an access_token, you can include it in subsequent HTTP requests using several methods:

    1. Authorization Header (Recommended): Authorization: Bearer {your_token_here}

    2. Query String Parameter: http://example.dev/me?token={your_token_here}

    3. Post Parameter

    4. Cookies

    5. Laravel Route Parameter

  4. Register the Service Provider (Laravel 5.4 or below)

    2.x

    If you are using Laravel 5.4 or an older version, you must manually register the service provider in your config/app.php file by adding Tymon\JWTAuth\Providers\LaravelServiceProvider::class to the providers array.

    'providers' => [
    
        ...
    
        Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
    ]
  5. Specify a guard when using multiple authentication guards

    2.x

    If the api guard is not your default guard, or if you have multiple guards configured, you must specify the guard name when calling the auth() helper to ensure you are interacting with the JWT authentication instance.

    $token = auth('api')->attempt($credentials);
  6. Create an AuthController for JWT authentication

    2.x

    An AuthController manages the lifecycle of a JWT session. Key operations include:

    • Login: Validates credentials using auth()->attempt($credentials) and returns a token.
    • Logout: Invalidates the current token using auth()->logout().
    • Refresh: Issues a new token using auth()->refresh().
    • Me: Retrieves the currently authenticated user via auth()->user().

    When protecting routes, use the auth:api middleware. You can exclude the login method from this middleware to allow users to authenticate.

    <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Support\Facades\Auth;
    use App\Http\Controllers\Controller;
    
    class AuthController extends Controller
    {
        public function __construct()
        {
            $this->middleware('auth:api', ['except' => ['login']]);
        }
    
        public function login()
        {
            $credentials = request(['email', 'password']);
    
            if (! $token = auth()->attempt($credentials)) {
                return response()->json(['error' => 'Unauthorized'], 401);
            }
    
            return $this->respondWithToken($token);
        }
    
        public function me()
        {
            return response()->json(auth()->user());
        }
    
        public function logout()
        {
            auth()->logout();
            return response()->json(['message' => 'Successfully logged out']);
        }
    
        public function refresh()
        {
            return $this->respondWithToken(auth()->refresh());
        }
    
        protected function respondWithToken($token)
        {
            return response()->json([
                'access_token' => $token,
                'token_type' => 'bearer',
                'expires_in' => auth()->factory()->getTTL() * 60
            ]);
        }
    }
  7. Bootstrap jwt-auth in Lumen

    2.x

    To integrate the package into the Lumen lifecycle, modify bootstrap/app.php with the following steps:

    1. Register Providers: Add the LumenServiceProvider and ensure your AuthServiceProvider is registered.
    2. Enable Auth Middleware: Uncomment the auth middleware in the routeMiddleware array.
    ```php
    // In bootstrap/app.php
    
    // Ensure this is uncommented
    $app->register(App\\
  8. Publish the jwt-auth configuration file

    2.x

    To create the config/jwt.php configuration file, run the Artisan vendor publish command specifying the Tymon\JWTAuth\Providers\LaravelServiceProvider provider. This file allows you to manage the package's core settings.

    php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
  9. Implement the JWTSubject contract on your User model

    2.x

    To use jwt-auth, your User model must implement the Tymon\JWTAuth\Contracts\JWTSubject interface. This requires defining two methods:

    1. getJWTIdentifier(): Returns the identifier that will be stored in the sub (subject) claim of the JWT (typically the primary key).
    2. getJWTCustomClaims(): Returns an associative array of custom claims to be added to the JWT payload. If no custom claims are needed, return an empty array [].
    <?php
    
    namespace App;
    
    use Tymon\JWTAuth\Contracts\JWTSubject;
    use Illuminate\Notifications\Notifiable;
    use Illuminate\Foundation\Auth\User 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 [];
        }
    }