Download the PHP package rbdwllr/reallysimplejwt without Composer
On this page you can find all versions of the php package rbdwllr/reallysimplejwt. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download rbdwllr/reallysimplejwt
More information about rbdwllr/reallysimplejwt
Files in rbdwllr/reallysimplejwt
Package reallysimplejwt
Short Description A really simple library to generate user authentication JSON Web Tokens.
License MIT
Informations about the package reallysimplejwt
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
- Create Token
- Validate Token
- Get Header and Payload Claims Data
- Build, Parse and Validate Factory Methods
- Non-Static Usage
- Advanced Usage
- Create Custom Token
- Access the Token
- Parse Token
- Access Token Claims Data
- Token Validation Methods
- Custom Encoding
- Error Messages and Codes
- Token Security
- Secret Strength
- 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:
The header and payload are both encoded JSON strings that contain a number of claims:
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:
Install via the composer.json file:
Add the following to your composer.json file:
Then run:
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.
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.
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.
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.
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.
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.
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.
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.
Access the Token
A ReallySimpleJWT\Jwt
object is returned when a developer calls the build()
method on the ReallySimpleJWT\Build
class. The Jwt class offers a single getToken()
method which returns the token string.
To parse a JSON Web Token via the ReallySimpleJWT\Parse
class a developer must first create a new ReallySimpleJWT\Jwt
object by injecting the token string on instantiation. The Jwt class will validate the structure of the token on instantiation to ensure integrity.
Parse Token
The ReallySimpleJWT\Parse
class allows a developer to parse a JWT and the parse()
method will decode the JSON Web Token and return the result as a ReallySimpleJWT\Parsed
object. This will provide access to the header and payload claims data the token holds.
Access Token Claims Data
The ReallySimpleJWT\Parsed
class is returned when a developer calls the parse()
method on the ReallySimpleJWT\Parse
class.
It provides a number of helper methods to gain access to the token claim data. A developer can call the getHeader()
and getPayload()
methods to gain access to the respective claim data as associative arrays.
Alternatively a developer can call one of the RFC compliant claim methods:
Header
getAlgorithm()
getType()
getContentType()
Payload
getIssuer()
getSubject()
getAudience()
getExpiration()
getNotBefore()
getIssuedAt()
getJwtId()
getExpiresIn()
getUsableIn()
Token Validation Methods
To Validate a JSON Web Token a developer can use the ReallySimpleJWT\Validate
class. To use the validate class you need to create and inject a ReallySimpleJWT\Parsed
object. This is so the validate class can access the information contained within the token.
Six validation methods are available which can all be chained:
signature()
confirms the token signature is valid.expiration()
confirms the token expiration claim (exp
) has not expired.notBefore()
confirms the token not before claim (nbf
) has elapsed.audience()
confirms the token audience claim (aud
) matches what is expected.algorithm()
confirms the token algorithm claim (alg
) matches what is expected and is valid (See: RFC 7518).algorithmNotNone()
confirms the token algorithm claim (alg
) is not set to none.
Each validation method will throw a ReallySimpleJWT\Exception\ValidateException
if there is anything wrong with the supplied token.
Custom Encoding
By default this library hashes and encodes the JWT signature via hash_hmac()
using the sha256 algorithm. If a developer would like to use a customised form of encoding they just need to generate a custom encode class which complies with the ReallySimpleJWT\Interfaces\Encode
interface. This can then be injected into the ReallySimpleJWT\Build
and ReallySimpleJWT\Validate
classes.
Error Messages and Codes
The ReallySimpleJWT library will in a number of situations throw exceptions to highlight problems when creating, parsing and validating JWT tokens. The error codes, messages and their explanations are in the table below.
There are six exception types that may be thrown:
ReallySimpleJWT\Exception\BuildException
ReallySimpleJWT\Exception\EncodeException
ReallySimpleJWT\Exception\JwtException
ReallySimpleJWT\Exception\ParsedException
ReallySimpleJWT\Exception\TokensException
ReallySimpleJWT\Exception\ValidateException
Code | Message | Explanation |
---|---|---|
1 | Token has an invalid structure. | Token must have three parts separated by dots. |
2 | Audience claim does not contain provided StringOrURI. | The aud claim must contain the provided string or URI string provided. |
3 | Signature is invalid. | Signature does not match header / payload content. Could not replicate signature with provided header, payload and secret. |
4 | Expiration claim has expired. | The exp claim must be a valid date time number in the future. |
5 | Not Before claim has not elapsed. | The nbf claim must be a valid date time number in the past. |
6 | The header claim [~claim~] is not set. | Attempt was made to access a header claim which does not exist. |
7 | The payload claim [~claim~] is not set. | Attempt was made to access a payload claim which does not exist. |
8 | Invalid payload claim. | Payload claims must be key value pairs of the format string: mixed . |
9 | Invalid secret. | Must be 12 characters in length, contain upper and lower case letters, a number, and a special character *&!@%^#$ |
10 | Algorithm claim is not valid. | Algorithm should be a valid Digital Signature or MAC Algorithm, or none. See RFC 7518. |
11 | Algorithm claim should not be none. | The alg claim should not be set to none. |
Token Security
The JWT RFC 7519 allows for the creation of tokens without signatures and without secured / hashed signatures. The ReallySimpleJWT library however imposes security by default as there is no logical reason not to. All created tokens must have a signature and a strong secret, but the library will parse and validate tokens without a secret or a strong secret. The library will not validate tokens without a signature.
By default The ReallySimpleJWT library makes available two encoding implementations, ReallySimpleJWT\Encoders\EncodeHS256
and ReallySimpleJWT\Encoders\EncodeHS256Strong
. The latter enforces strict secret security and is used by default to create tokens via the Token
and Tokens
classes. The EncodeHS256
does not impose strict secret security and can be used with the Build
class to create tokens when required. In addition,
it is possible to create a custom encode class by implementing the ReallySimpleJWT\Interfaces\Encode
interface. See the section Custom Encoding.
Secret Strength
This JWT library imposes strict secret security via the EncodeHS256Strong
class. The secret provided must be at least 12 characters in length; contain numbers; upper and lowercase letters; and one of the following special characters *&!@%^#$
.
The reason for this is that there are lots of JWT Crackers available meaning weak secrets are easy to crack thus rendering the signature security JWT offers useless.
Framework Integration With PSR-JWT Middleware
You can easily integrate ReallySimpleJWT with PSR-7 / PSR-15 compliant frameworks such as Slim PHP and Laminas by using the PSR-JWT library.
For example integration with Slim PHP only requires a few lines of code:
Please read the PSR-JWT documentation to learn more about integration options for ReallySimpleJWT.
Browser Integration With RS-JWT
When you create JSON Web Tokens you may wish to read some of the information contained in the header and payload claims in the browser.
If you do, we have an NPM packages for that called RS-JWT.
Install:
Usage:
For more information see the project README or visit the NPM Page.
License
MIT
Author
Rob Waller
Twitter: @RobDWaller