Skip to content

For Signing and Verifying JSON Web Tokens in Code Igniter.

License

Notifications You must be signed in to change notification settings

francis94c/ci-jwt

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

82 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Build Status Coverage Status Maintainability Scrutinizer Code Quality Latest Release Commits

JWT

JWT

JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties.

JWT.IO allows you to decode, verify and generate JWT.

This library does not support JWE, JOSE, or Asymetric Key Signing, but basic anti-tamper checks which the RFC 7519 standards define.

For good security or encryption, consider using PASETO.

Installation

Download and Install Splint from https://splint.cynobit.com/downloads/splint and run the below from the root of your Code Igniter project.

splint install francis94c/ci-jwt

Documentation

Here's an example Usage. Load the package and initialize as needed. Then sign or verify token.

$this->load->package("francis94c/ci-jwt");
$params = [
  "secret"         => "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
  "algorithm"      => "HS512",
  "allow_unsigned" => false,
  "set_iat"        => true,
  "auto_expire"    => "+30 Days"
];
$this->jwt->init($params);

// Create Token.
$this->jwt->header("alg", JWT::HS384);
$this->jwt->payload("sub", "john");
$this->jwt->payload("iss", "www.example.com");
$this->jwt->expire("+5 Days");
$token = $this->jwt->sign();

// Process a Token.
if ($this->jwt->verify($token)) {
  $this->jwt->create(); // Clears payload and header array. This is required when working with fresh token data.
  $this->jwt->decode($token);
  $sub = $this->jwt->payload()["sub"];
  $iss = $this->jwt->payload("iss");
  // Other Procedures Here.
} else {
  echo "Invalid Token!";
}

You can also load and initialize the package globally by simply creating a cong file named jwt.php in application\config. The file should have the contents like below.

defined('BASEPATH') OR exit('No direct script access allowed');

$config["jwt"] = [
  "secret"         => "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
  "algorithm"      => "HS512",
  "allow_unsigned" => false,
  "set_iat"        => true,
  "auto_expire"    => "+30 Days"
]

The $config array must have the key jwt as above. Then you can simply load the package anywhere the CI instance as below.

$this->load->package("francis94c/ci-jwt");

Config/Initialization Parameters

Name Description
secret The Secret Key used to Sign and Verify Tokens
algorithm The Algorithm used to Sign and Verify Tokens. e.g. HS256
allow_unsigned Set this to true if you want the verify function to return true for unsigned token. This config is set to false by default. For security reason. leave it at that, Unless you know what you are doing.
set_iat Set this to true if you want the iat claim to be set to the time the token was created when you extract/sign the token by calling the sign() function.
auto_expire Sets the time at which all tokens generated should be considered expired automatically.

Methods

init(array $config):void

This method allows you to set a couple of options that influences the behaviour of the library.

Example
$this->jwt->init([
  "algorithm"   => JWT::HS512,
  "auto_expire" => "+30 Days"
]);

create():void

Essentially creates a new token. This results in the clearing of the header and payload array for input of fresh data.

Example
$this->jwt->create();

header(string $key, string|int|array $value):?string|int|array

This method adds an item in the Token's header section. Note: You don't have to always set a header field, unless you want to change the signing algorithm for the current token other than the default set with init() as you can see from the example below. It returns the value of the given key if the $value argument is not supplied.

Example
$this->jwt->header("alg", JWT::HS512);
// Supported algorithms are HS256, HS512, & HS384

$alg = $this->jwt->header("alg");

payload(string $key, string|int|array $value):?string|int|array

This method adds an item (string, int array, It's JSON after all) to the payload section of an array. It returns the value of the given key if the $value argument is not supplied.

Example
$this->jwt->payload("sub", "username");
// OR
$this->jwt->sub("username");

// ============

$sub = $this->jwt->payload("sub");
// OR
$sub = $this->jwt->sub();

sign([string $secret]):?string

This method generates a signed token (JWT), using the secret set with the init() function or the $secret argument if supplied. All tokens must have a payload. headers are automatically generated for you if you don't set them.

Example
$token = $this->jwt->sign();
echo $token;
// OR
$token = $this->jwt->sign("A_SECRET_KEY_HERE");
echo $token;

token():?string

Returns an unsigned token. will return null if payload is empty. All tokens must have a payload. headers are automatically generated for you if you don't set them.

Example
$token = $this->jwt->token();
echo $token;

verify(string $jwt, [string $secret]):bool

Verifies the signature of the given $jwt and returns true if the check passes. NB: If an unsigned $jwt is provided and the allow_unsigned flag is set to true, the function will automatically return true. If a $secret is provided with this function, it will use that instead of the one originally set using init or a config file.

Example
if ($this->jwt->verify($jwt)) {
  echo "Successfully Verified Token.";
} else {
  echo "Very Very Bad Token.";
}

expire(string $when):void

Set's the current token to expire at a given time $when. You'll usually call this function before calling sign() or token() to get the actual JWT whose expiry date has been set with this function.

This functions internally calls PHP's strtotime function, passing it the $when argument and setting the return value of this function (a timestamp) to the exp claim/key of the payload.

See https://www.php.net/manual/en/function.strtotime.php for an overview of strtotime.

Example
$this->jwt->expire("+1 Day");

expired(string $jwt):bool

Checks if token is expired. Returns true if expired, false if not.

Example
$this->jwt->expired($jwt);

decode(string $jwt):bool

Decodes the given $jwt and sets the contents of it's payload accessible with $this->jwt->payload() to the payload of the $jwt and the header accessible with $this->jwt->header to the header of the $jwt. This function does not verify the token. The token only need be a valid JWT. to verify the token, use the $this->jwt->verify($jwt). This function returns true if successful, false if not.

Example
$this->jwt->decode($jwt);