dev-master
9999999-dev https://github.com/andrewdyer/jwt-auth
MIT
The Requires
- php >=7.0.0
- nesbot/carbon ^1.32
- firebase/php-jwt ^5.0
The Development Requires
by Andrew Dyer
php auth jwt
Wallogit.com
2017 © Pedro Peláez
, (*1)
A simple framework-agnostic JSON Web Token authentication solution., (*2)
Licensed under the MIT license and is free for private or commercial projects., (*3)
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., (*4)
composer require andrewdyer/jwt-auth
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., (*5)
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., (*6)
Create an authentication provider class that implements AuthProviderInterface. This class will handle credential validation and user retrieval by ID., (*7)
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., (*8)
Create a JWT provider class that implements JWTProviderInterface. This class should handle encoding and decoding JWT tokens., (*9)
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., (*10)
The ClaimsFactory class helps create a JWT claims instance. The build method accepts an array of claims and returns an instance of ClaimsInterface., (*11)
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., (*12)
Create a new instance of the JWTAuth class. This requires an instance of AuthProviderInterface, JWTProviderInterface, and ClaimsInterface., (*13)
use App\Providers\AuthProvider; use App\Providers\JWTProvider; use Anddye\JWTAuth\JWTAuth; $authProvider = new AuthProvider(); $jwtProvider = new JWTProvider(); $jwtAuth = new JWTAuth($authProvider, $jwtProvider, $claims);
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., (*14)
try {
$token = $jwtAuth->attempt('admin', 'secret');
echo "Token: " . $token;
} catch (\Anddye\JWTAuth\Exceptions\InvalidCredentialsException $e) {
echo "Invalid credentials";
}
Validate a JWT token and retrieve the associated user (subject)., (*15)
$subject = $jwtAuth->authenticate('your-jwt-token-here');
if ($subject) {
echo "User authenticated!";
} else {
echo "Invalid token";
}
MIT
php auth jwt