ReallySimpleJWT
A really simple library to generate JSON Web Tokens in PHP.
Install / Use
/learn @RobDWaller/ReallySimpleJWTREADME
Really Simple JSON Web Tokens
A simple PHP library for creating JSON Web Tokens that uses HMAC SHA256 to sign signatures. For basic usage the library exposes a static interface to allow developers to create a token that stores a user identifier and expiration time.
The library is also open to extension, developers can define their own encoding and secret standards, set all the RFC standard JWT claims, and set their own private claims.
You can easily integrate ReallySimpleJWT with PSR-7 / PSR-15 compliant frameworks such as Slim PHP with the PSR-JWT middleware library. Please read the framework integration documentation to learn more.
If you need to read tokens in the browser please take a look at our JavaScript / Typescript library RS-JWT.
Contents
- What is a JSON Web Token?
- Setup
- Basic Usage
- Advanced Usage
- Error Messages and Codes
- Token Security
- Framework Integration With PSR-JWT Middleware
- Browser Integration With RS-JWT
What is a JSON Web Token?
JSON Web Tokens is a standard for creating URL friendly access tokens that assert claims about a user or system.
A token is broken down into three parts; the header, the payload and the signature; with each part separated by a dot. Each part is encoded using the base64URL standard, see the RFC.
An example JWT:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
The header and payload are both encoded JSON strings that contain a number of claims:
// Example Header
{
"alg": "HS256",
"typ": "JWT"
}
// Example Payload
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022
}
A claim is a key value pair, eg "typ": "JWT", please read RFC 7519 to learn more about JSON Web Token claims.
Token security is achieved via the signature which is made up of the header, payload and a secret known only to the token author. This information is hashed and then base64URL encoded.
If a malicious user attempts to edit the header or payload claims they will be unable to replicate the signature so long as you use a strong secret. See Token Security for more information on this.
Setup
To install this package you will need to install Composer and then run composer init. Once this is done you can install the package via the command line or by editing the composer.json file created by the composer init command.
Finally you will need to reference the composer autoloader in your PHP code, require 'vendor/autoload.php';. The location of the autoload file will differ dependent on where your code is run and may not be required if you are using a framework.
Install via Composer on the command line:
composer require rbdwllr/reallysimplejwt
Install via the composer.json file:
Add the following to your composer.json file:
"require": {
"rbdwllr/reallysimplejwt": "^5.0"
}
Then run:
composer update
Basic Usage
For basic usage the library exposes a set of static methods via the ReallySimpleJWT\Token class which allow a developer to create and validate basic JSON Web Tokens.
Create Token
Call the create() static method and pass in a user identifier, a secret, an expiration date time number and the token issuer.
This will return a token string on success and throw a ReallySimpleJWT\Exception\BuildException on failure.
use ReallySimpleJWT\Token;
$userId = 12;
$secret = 'sec!ReT423*&';
$expiration = time() + 3600;
$issuer = 'localhost';
$token = Token::create($userId, $secret, $expiration, $issuer);
To create a more customised token developers can use the customPayload() method. This allows the creation of a token based on an array of key value pairs which represent the payload claims.
use ReallySimpleJWT\Token;
$payload = [
'iat' => time(),
'uid' => 1,
'exp' => time() + 10,
'iss' => 'localhost'
];
$secret = 'Hello&MikeFooBar123';
$token = Token::customPayload($payload, $secret);
On success the customPayload() method will return a JWT token string and on failure it will throw an exception.
Validate Token
To validate a JSON web token call the validate() static method, pass in the token string and the secret. The validate method checks the token structure is correct and the signature is valid.
It will return true on success and false on failure.
use ReallySimpleJWT\Token;
$token = 'aaa.bbb.ccc';
$secret = 'sec!ReT423*&';
$result = Token::validate($token, $secret);
There are also methods available to validate the token's expiration claim and not before claim. Both will return true on success and false on failure.
use ReallySimpleJWT\Token;
$token = 'aaa.bbb.ccc';
Token::validateExpiration($token);
Token::validateNotBefore($token);
Get Header and Payload Claims Data
To retrieve the token claims data from the header or payload call the getHeader() and or getPayload() static methods.
Both methods will return an associative array on success and throw an exception on failure.
use ReallySimpleJWT\Token;
$token = 'aaa.bbb.ccc';
// Return the header claims
Token::getHeader($token);
// Return the payload claims
Token::getPayload($token);
Build, Parse and Validate Factory Methods
The ReallySimpleJWT\Token class also provides three factory methods to gain access to the core ReallySimpleJWT\Build, ReallySimpleJWT\Parse, and ReallySimpleJWT\Validate classes. These classes allow you to build custom tokens, and parse and validate tokens as you see fit.
Token::builder(); // Returns an instance of ReallySimpleJWT\Build
Token::parser($token); // Returns an instance of ReallySimpleJWT\Parse
Token::validator($token, $secret); // Returns an instance of ReallySimpleJWT\Validate
Non-Static Usage
The ReallySimpleJWT\Token class is just a wrapper for the ReallySimpleJWT\Tokens class which can be used directly for those who'd prefer to instantiate and inject the functionality.
use ReallySimpleJWT\Tokens;
$tokens = new Tokens();
$id = 52;
$secret = 'sec!ReT423*&';
$expiration = time() + 50;
$issuer = 'localhost';
$token = $tokens->create('id', $id, $secret, $expiration, $issuer);
$token->getToken();
Please note when calling the create() and customPayload() methods on the Tokens class they will return an instance of the Jwt class unlike the Token class which will return a token string.
In addition, the create() method has a slightly different signature to the Tokens class as a user identifier key must be passed in.
create(string $userKey, $userId, string $secret, int $expiration, string $issuer): Jwt
Advanced Usage
To create customised JSON Web Tokens developers need to access the ReallySimpleJWT\Build, ReallySimpleJWT\Parse and ReallySimpleJWT\Validate classes directly.
Create Custom Token
The ReallySimpleJWT\Build class allows you to create a completely unique JSON Web Token. It has helper methods for all the RFC defined header and payload claims. For example, the setIssuer() method will add the iss claim to the token payload.
The class also allows developers to set custom header and payload claims via the setHeaderClaim() and setPayloadClaim() methods.
The methods can be chained together and when the build() method is called the token will be generated and returned as a ReallySimpleJWT\Jwt object.
use ReallySimpleJWT\Build;
use ReallySimpleJWT\Helper\Validator;
use ReallySimpleJWT\Encoders\EncodeHS256;
$secret = '!secReT$123*';
$build = new Build('JWT', new Validator(), new EncodeHS256($secret));
$token = $build->setContentType('JWT')
->setHeaderClaim('info', 'foo')
->setIssuer('localhost')
->setSubject('admins')
->setAudience('https
Related Skills
node-connect
338.7kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
83.6kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
338.7kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
commit-push-pr
83.6kCommit, push, and open a PR
