Simple JWT implementation
Christopher Vagnetoft
f83998e6c7
* Properly check nbf and exp claims in token to determine simple validity. * Properly check nbf and exp claims in validator and throw exceptions if expired/not yet valid. |
||
---|---|---|
src | ||
tests | ||
.gitignore | ||
.woodpecker.yml | ||
CHANGELOG.md | ||
composer.json | ||
phpstan.neon | ||
phpunit.xml | ||
README.md |
SimpleJWT
This is a simple library for generating (signing) and verifying JWT tokens. It is by no means an advanced library. If you just need to sign and refresh tokens for users of your site or intranet, this will work great. If you need all the glorious features of the JWT spec you should look elsewhere.
- Only handles HMAC-SHA256.
- Only handles expiry ('exp') natively
- Doesn't use any X.509 stuff.
Use Cases
Use this to avoid having to rewrite the wheel when implementing authorization internally within a system where OAuth may be overkill.
- Make good use of the expiry. JWTs aren't armored in any way, so make sure they can't be used longer than they have to. (An hour is a good idea)
- Make sure you understand the security aspects of JWTs.
Installation
Install using composer:
$ composer require noccylabs/simple-jwt:@dev
Usage
You need a key for both generating and parsing tokens. Create a JWTDerivedKey
or a JWTPlaintextKey
and pass it to the JWTToken
constructor:
use NoccyLabs\SimpleJWT\Key\{JWTDerivedKey,JWTPlaintextKey}
// Derive a key using secret and salt...
$key = new JWTDerivedKey("secret", "salt");
// ...or use a prepared plaintext key
$key = new JWTPlaintextKey("This Should Be Binary Data..");
JWTDerivedKey
uses hash_pbkdf2.
Generating tokens
use NoccyLabs\SimpleJWT\JWTToken;
$tok = new JWTToken($key);
$tok->setExpiry("1h");
$tok->claims->add("some/claim/MaxItems", 8);
$str = $tok->getSignedToken();
Parsing tokens
Parsing is done by passing the raw token as the 2nd parameter
use NoccyLabs\SimpleJWT\JWTToken;
$str = "...received token...";
$tok = new JWTToken($key, $str);
if (!$tok->isValid()) {
// This check works, but using the validator might be better
}
// Using ->has() follwed by ->get() is one way
if ($tok->claims->has("some/claim/MaxItems")) {
// The claim exists, we can get the value (if any)
$val = $tok->claims->get("some/claim/MaxItems");
}
// You can also use valueOf() to return a default value if needed
$val = $tok->claims->valueOf("some/claim/MaxItems", 64);
Validating tokens
use NoccyLabs\SimpleJWT\Validator\JWTValidator;
$validator = new JWTValidator();
// Require that some claim exists
$validator
->requireIssuer("api.issuer.tld")
->requireAudience(["api.issuer.tld", "foo.issuer.tld"])
->addRequiredClaim("some/required/Claim");
try {
// Pass a JWTToken to validateToken()...
$valid = $validator->validateToken($tok);
// ...or pass a JWTKeyInterface and the raw string to validate()
$valid = $validator->validate($key, $tokenstr);
}
catch (JWTValidatorException $e) {
// validation failed
}