### Install JWT Auth via Composer Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/laravel-installation.md Use Composer to install the latest version of the JWT Auth package. ```bash composer require php-open-source-saver/jwt-auth ``` -------------------------------- ### Login User and Get Token Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Use the login() method to log in a user and obtain a JWT for them. ```php // Get some user from somewhere $user = User::first(); // Get the token $token = auth()->login($user); ``` -------------------------------- ### Get Authenticated User or Throw Exception Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Use userOrFail() to get the authenticated user or throw a UserNotDefinedException if the user is not set. ```php try { $user = auth()->userOrFail(); } catch (\ ``` -------------------------------- ### userOrFail() Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Get the currently authenticated user or throw a UserNotDefinedException if the user is not set. ```APIDOC ## userOrFail() Get the currently authenticated user or throw an exception. ```php try { $user = auth()->userOrFail(); } catch (\/PHPOpenSourceSaver\/JWTAuth\/Exceptions\/UserNotDefinedException $e) { // do something } ``` If the user is not set, then a `PHPOpenSourceSaver\JWTAuth\Exceptions\UserNotDefinedException` will be thrown. ``` -------------------------------- ### tokenById() Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Get a JWT based on a given user's ID. ```APIDOC ## tokenById() Get a token based on a given user's id. ```php $token = auth()->tokenById(123); ``` ``` -------------------------------- ### user() Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Get the currently authenticated user. Returns null if the user is not authenticated. ```APIDOC ## user() Get the currently authenticated user. ```php // Get the currently authenticated user $user = auth()->user(); ``` If the user is not then authenticated, then `null` will be returned. ``` -------------------------------- ### Get Token by User ID Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Retrieve a JWT based on a given user's ID. ```php $token = auth()->tokenById(123); ``` -------------------------------- ### payload() Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Get the raw JWT payload, allowing access to claims like 'sub', 'jti', and 'exp'. ```APIDOC ## payload() Get the raw JWT payload. ```php $payload = auth()->payload(); // then you can access the claims directly e.g. $payload->get('sub'); // = 123 $payload['jti']; // = 'asfe4fq434asdf' $payload('exp') // = 123456 $payload->toArray(); // = ['sub' => 123, 'exp' => 123456, 'jti' => 'asfe4fq434asdf'] etc ``` ``` -------------------------------- ### Get JWT Payload Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Retrieve the raw JWT payload and access its claims directly. ```php $payload = auth()->payload(); // then you can access the claims directly e.g. $payload->get('sub'); // = 123 $payload['jti']; // = 'asfe4fq434asdf' $payload('exp') // = 123456 $payload->toArray(); // = ['sub' => 123, 'exp' => 123456, 'jti' => 'asfe4fq434asdf'] etc ``` -------------------------------- ### Override Token Time To Live (TTL) Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Set a custom TTL for JWTs, overriding the default expiration time. This example sets it to 2 hours. ```php $token = auth()->setTTL(120)->attempt($credentials); ``` -------------------------------- ### Example JWT Login Response Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/quick-start.md A successful login request returns a JSON object containing the JWT access token, token type, and expiration time. This token is used for subsequent authenticated requests. ```json { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ", "token_type": "bearer", "expires_in": 3600 } ``` -------------------------------- ### Get Authenticated User Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Retrieve the currently authenticated user using the user() method. Returns null if no user is authenticated. ```php // Get the currently authenticated user $user = auth()->user(); ``` -------------------------------- ### Override the token ttl Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Override the token time-to-live (TTL) to set a custom expiration duration, for example, 2 hours. ```APIDOC ## Override the token ttl This example sets the token to expire after 2 hours. ```php $token = auth()->setTTL(120)->attempt($credentials); ``` ``` -------------------------------- ### login() Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Log a user in and return a JWT for them. ```APIDOC ## login() Log a user in and return a jwt for them. ```php // Get some user from somewhere $user = User::first(); // Get the token $token = auth()->login($user); ``` ``` -------------------------------- ### Publish JWT Auth Configuration Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/laravel-installation.md Publish the package's configuration file to your Laravel project. ```bash php artisan vendor:publish --provider="PHPOpenSourceSaver\JWTAuth\Providers\LaravelServiceProvider" ``` -------------------------------- ### Create and Implement AuthController Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/quick-start.md Create an AuthController to handle user authentication logic, including login, logout, refreshing tokens, and retrieving user details. This controller uses the JWTSubject methods for token generation. ```bash php artisan make:controller AuthController ``` ```php middleware('auth:api', ['except' => ['login']]); } /** * Get a JWT via given credentials. * * @return \Illuminate\Http\JsonResponse */ public function login() { $credentials = request(['email', 'password']); if (! $token = auth()->attempt($credentials)) { return response()->json(['error' => 'Unauthorized'], 401); } return $this->respondWithToken($token); } /** * Get the authenticated User. * * @return \Illuminate\Http\JsonResponse */ public function me() { return response()->json(auth()->user()); } /** * Log the user out (Invalidate the token). * * @return \Illuminate\Http\JsonResponse */ public function logout() { auth()->logout(); return response()->json(['message' => 'Successfully logged out']); } /** * Refresh a token. * * @return \Illuminate\Http\JsonResponse */ public function refresh() { return $this->respondWithToken(auth()->refresh()); } /** * Get the token array structure. * * @param string $token * * @return \Illuminate\Http\JsonResponse */ protected function respondWithToken($token) { return response()->json([ 'access_token' => $token, 'token_type' => 'bearer', 'expires_in' => auth()->factory()->getTTL() * 60 ]); } } ``` -------------------------------- ### Generate RSA Certificate with Specific Parameters Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/generate-secrets.md Generates a 4096-bit RSA certificate using SHA 512 hashing. The --force flag will override existing certificates. ```bash php artisan jwt:generate-certs --force --algo=rsa --bits=4096 --sha=512 ``` -------------------------------- ### Define API Authentication Routes Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/quick-start.md Add basic authentication routes in routes/api.php for login, logout, refresh, and fetching user information. These routes are protected by the 'api' middleware. ```php Route::group([ 'middleware' => 'api', 'prefix' => 'auth' ], function ($router) { Route::post('login', 'AuthController@login'); Route::post('logout', 'AuthController@logout'); Route::post('refresh', 'AuthController@refresh'); Route::post('me', 'AuthController@me'); }); ``` -------------------------------- ### attempt() Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Attempt to authenticate a user via provided credentials. Returns a JWT upon successful authentication or null if credentials are invalid. ```APIDOC ## attempt() Attempt to authenticate a user via some credentials. ```php // Generate a token for the user if the credentials are valid $token = auth()->attempt($credentials); ``` This will return either a jwt or `null` ``` -------------------------------- ### Generate JWT Certificates Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/generate-secrets.md Use this command to generate RSA or EC certificates for signing JWT tokens. It updates the .env file with the new certificate paths. ```bash php artisan jwt:generate-certs ``` -------------------------------- ### Attempt Authentication Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Use the attempt() method to authenticate a user based on provided credentials and generate a JWT. ```php // Generate a token for the user if the credentials are valid $token = auth()->attempt($credentials); ``` -------------------------------- ### Register JWT Configuration in Lumen Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/lumen-installation.md Copy the configuration file to your Lumen application's config directory and register it in bootstrap/app.php. ```php $app->configure('jwt'); ``` -------------------------------- ### Generate EC Certificate with Specific Parameters Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/generate-secrets.md Generates an Elliptic Curve (EC) certificate using the prime256v1 curve and SHA 512 hashing. The --force flag will override existing certificates. ```bash php artisan jwt:generate-certs --force --algo=ec --curve=prime256v1 --sha=512 ``` -------------------------------- ### Generate JWT Secret Key Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/generate-secrets.md Use this command to generate a secret key for signing JWT tokens. It will update your .env file. ```bash php artisan jwt:secret ``` -------------------------------- ### Configure Auth Guard for JWT Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/quick-start.md Modify the config/auth.php file to use the 'jwt' driver for the 'api' guard. This enables jwt-auth to handle authentication for your API routes. ```php 'defaults' => [ 'guard' => 'api', 'passwords' => 'users', ], ... 'guards' => [ 'api' => [ 'driver' => 'jwt', 'provider' => 'users', ], ], ``` -------------------------------- ### Specify Guard for Authentication Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md When multiple guards are defined or the 'api' guard is not the default, specify the guard when calling auth(). ```php $token = auth('api')->attempt($credentials); ``` -------------------------------- ### Multiple Guards Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md When using multiple authentication guards or if the 'api' guard is not the default, you must specify the guard when calling auth(). ```APIDOC ## Multiple Guards If the newly created 'api' guard is not set as a default guard or you have defined multiple guards to handle authentication, you should specify the guard when calling auth(). ```php $token = auth('api')->attempt($credentials); ``` ``` -------------------------------- ### logout() Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Log the user out, invalidating the current token and unsetting the authenticated user. Optionally, force the token to be blacklisted forever. ```APIDOC ## logout() Log the user out - which will invalidate the current token and unset the authenticated user. ```php auth()->logout(); // Pass true to force the token to be blacklisted "forever" auth()->logout(true); ``` ``` -------------------------------- ### JWT Secret Configuration Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/configuration.md Configure the JWT secret key using an environment variable. ```php 'secret' => env('JWT_SECRET'), ``` -------------------------------- ### Add Custom Claims to Token Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Add custom claims to the JWT when attempting authentication. ```php $token = auth()->claims(['foo' => 'bar'])->attempt($credentials); ``` -------------------------------- ### Register JWT Auth Service Provider in Lumen Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/lumen-installation.md Add the Lumen Service Provider for JWT Auth to your application's bootstrap/app.php file. ```php // Uncomment this line $app->register(App\Providers\AuthServiceProvider::class); // Add this line $app->register(PHPOpenSourceSaver\JWTAuth\Providers\LumenServiceProvider::class); ``` -------------------------------- ### Adding custom claims Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Add custom claims to the token when attempting authentication. ```APIDOC ## Adding custom claims ```php $token = auth()->claims(['foo' => 'bar'])->attempt($credentials); ``` ``` -------------------------------- ### validate() Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Validate a user's credentials. ```APIDOC ## validate() Validate a user's credentials. ```php if (auth()->validate($credentials)) { // credentials are valid } ``` ``` -------------------------------- ### Set the request instance explicitly Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Set the request instance explicitly on the guard instance to retrieve user information. ```APIDOC ## Set the request instance explicitly ```php $user = auth()->setRequest($request)->user(); ``` ``` -------------------------------- ### Set the token explicitly Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Set the token explicitly on the guard instance to retrieve user information. ```APIDOC ## Set the token explicitly ```php $user = auth()->setToken('eyJhb...')->user(); ``` ``` -------------------------------- ### Set Request Instance Explicitly Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Manually set the request instance to be used for authentication operations. ```php $user = auth()->setRequest($request)->user(); ``` -------------------------------- ### refresh() Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Refresh a token, invalidating the current one. Optionally, force the token to be blacklisted forever and reset claims. ```APIDOC ## refresh() Refresh a token, which invalidates the current one. ```php $newToken = auth()->refresh(); // Pass true as the first param to force the token to be blacklisted "forever". // The second parameter will reset the claims for the new token $newToken = auth()->refresh(true, true); ``` ``` -------------------------------- ### Register Service Provider (Laravel 5.4 and below) Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/laravel-installation.md Add the JWTAuth service provider to your Laravel application's config/app.php file for versions 5.4 and below. ```php 'providers' => [ ... PHPOpenSourceSaver\JWTAuth\Providers\LaravelServiceProvider::class, ] ``` -------------------------------- ### Implement JWTSubject Contract in User Model Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/quick-start.md Update your User model to implement the JWTSubject contract, which requires the getJWTIdentifier and getJWTCustomClaims methods. This is essential for generating JWT tokens. ```php getKey(); } /** * Return a key value array, containing any custom claims to be added to the JWT. * * @return array */ public function getJWTCustomClaims() { return []; } } ``` -------------------------------- ### Uncomment Auth Middleware in Lumen Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/lumen-installation.md Ensure the 'auth' middleware is uncommented in your bootstrap/app.php file. ```php $app->routeMiddleware([ 'auth' => App\Http\Middleware\Authenticate::class, ]); ``` -------------------------------- ### Set Token Explicitly Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Manually set the JWT to be used for authentication operations. ```php $user = auth()->setToken('eyJhb...')->user(); ``` -------------------------------- ### Refresh Token Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Refresh a token to invalidate the current one and generate a new one. Optionally, force blacklisting and reset claims. ```php $newToken = auth()->refresh(); // Pass true as the first param to force the token to be blacklisted "forever". // The second parameter will reset the claims for the new token $newToken = auth()->refresh(true, true); ``` -------------------------------- ### Logout User and Invalidate Token Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Log a user out by invalidating their current token and unsetting the authenticated user. Optionally, force token blacklisting. ```php auth()->logout(); // Pass true to force the token to be blacklisted "forever" auth()->logout(true); ``` -------------------------------- ### Configure Custom TTL for JWT Guards Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/configuration.md Set custom Time To Live (TTL) values for individual JWT authentication guards. This allows for different token expiration policies per guard, overriding the global TTL. If no 'ttl' is specified for a guard, it defaults to the global 'ttl' setting in config/jwt.php. ```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', ], ], ``` -------------------------------- ### Validate Credentials Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Validate a user's credentials without logging them in. ```php if (auth()->validate($credentials)) { // credentials are valid } ``` -------------------------------- ### Configure JWT Cookie Name Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/quick-start.md Customize the name of the cookie used to store the JWT token. This configuration is essential for cookie-based authentication. ```php return [ // ... 'cookie_name' => 'token', // ... ]; ``` -------------------------------- ### invalidate() Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Invalidate the token by adding it to the blacklist. Optionally, force the token to be blacklisted forever. ```APIDOC ## invalidate() Invalidate the token (add it to the blacklist). ```php auth()->invalidate(); // Pass true as the first param to force the token to be blacklisted "forever". auth()->invalidate(true); ``` ``` -------------------------------- ### Invalidate Token Source: https://github.com/php-open-source-saver/jwt-auth/blob/main/docs/auth-guard.md Invalidate the current token by adding it to the blacklist. Optionally, force permanent blacklisting. ```php auth()->invalidate(); // Pass true as the first param to force the token to be blacklisted "forever". auth()->invalidate(true); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.