andrewdyer / jwt-auth
A simple framework agnostic JSON Web Token authentication solution
Installs: 331
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 0
pkg:composer/andrewdyer/jwt-auth
Requires
- php: ^8.2
Requires (Dev)
- firebase/php-jwt: ^6.10
- phpunit/phpunit: ^11.5
README
π JWT Auth
A simple framework-agnostic JSON Web Token authentication solution.
π License
Licensed under the MIT license and is free for private or commercial projects.
β¨ Introduction
JWT Auth provides a straightforward way to implement JSON Web Token (JWT) authentication in any PHP application. The library offers an easy-to-use interface for generating and validating JWTs, supports custom authentication providers, and provides flexible claims generation and validation. Additionally, it ensures secure token encoding and decoding.
π₯ Installation
composer require andrewdyer/jwt-auth
π Getting Started
1. Define the JWT Subject
Create a class (e.g., User) that implements the JWTSubject interface. This class must provide a method getJWTIdentifier to return the userβs unique identifier.
namespace App\Models; use Anddye\JWTAuth\Interfaces\JWTSubject; class User implements JWTSubject { public function getJWTIdentifier(): int { return 1; } }
Note: This example is simplified for demonstration purposes. In a real-world application, you would typically use a proper user model, such as one provided by your framework. Ensure the
getJWTIdentifiermethod returns a unique user identifier appropriate for your system.
2. Create an Authentication Provider
Create an authentication provider class that implements AuthProviderInterface. This class will handle credential validation and user retrieval by ID.
namespace App\Providers; use Anddye\JWTAuth\Interfaces\AuthProviderInterface; use App\Models\User; class AuthProvider implements AuthProviderInterface { public function byCredentials(string $username, string $password) { if ($username === 'admin' && $password === 'secret') { return new User(); } return null; } public function byId(int $id) { if ($id === 1) { return new User(); } return null; } }
Note: This example uses hardcoded credentials for demonstration purposes. In a real-world application, you should validate credentials securely by checking against a database and using hashed passwords (e.g., via libraries like
bcryptorpassword_hash). Ensure you follow best practices for secure authentication.
3. Create a JWT Provider
Create a JWT provider class that implements JWTProviderInterface. This class should handle encoding and decoding JWT tokens.
namespace App\Providers; use Anddye\JWTAuth\Interfaces\JWTProviderInterface; class JWTProvider implements JWTProviderInterface { public function decode(string $token) { return json_decode(base64_decode($token), true); } public function encode(array $claims): string { return base64_encode(json_encode($claims)); } }
Note: This examples used
base64_encodeandbase64_decodefor simplicity. For real-world usage, consider using a proper JWT library such as firebase/php-jwt for better security.
4. Generate JWT Claims
The ClaimsFactory class helps create a JWT claims instance. The build method accepts an array of claims and returns an instance of ClaimsInterface.
use Anddye\JWTAuth\Factory\ClaimsFactory; $claims = ClaimsFactory::build([ 'iss' => 'https://example.com', // Issuer of the JWT 'aud' => 'https://example.com', // Audience of the JWT 'exp' => 1582243200, // Expiration time (Unix timestamp) 'nbf' => 1582193571, // Not before time (Unix timestamp) 'iat' => 1582193571, // Issued at time (Unix timestamp) 'jti' => 'fVcx9BJHqh', // Unique identifier ]);
Note: This example uses hardcoded Unix timestamps for demonstration purposes. Consider using libraries like nesbot/carbon or PHP's native
DateTimeclass to generate timestamps dynamically. This helps improve readability and ensures accurate date handling.
5. Initialize the JWT Authenticator
Create a new instance of the JWTAuth class. This requires an instance of AuthProviderInterface, JWTProviderInterface, and ClaimsInterface.
use App\Providers\AuthProvider; use App\Providers\JWTProvider; use Anddye\JWTAuth\JWTAuth; $authProvider = new AuthProvider(); $jwtProvider = new JWTProvider(); $jwtAuth = new JWTAuth($authProvider, $jwtProvider, $claims);
π Usage
Attempt Authentication
Authenticate a user by providing their credentials. If successful, a JWT token will be returned. If the credentials are invalid, an InvalidCredentialsException will be thrown.
try { $token = $jwtAuth->attempt('admin', 'secret'); echo "Token: " . $token; } catch (\Anddye\JWTAuth\Exceptions\InvalidCredentialsException $e) { echo "Invalid credentials"; }
Authenticate a Token
Validate a JWT token and retrieve the associated user (subject).
$subject = $jwtAuth->authenticate('your-jwt-token-here'); if ($subject) { echo "User authenticated!"; } else { echo "Invalid token"; }
