PHPackages                             quankim/cakephp-jwt-auth - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. quankim/cakephp-jwt-auth

ActiveCakephp-plugin

quankim/cakephp-jwt-auth
========================

QuanKim/JwtAuth plugin for CakePHP 3

1.1(9y ago)01811PHPPHP &gt;=5.4.16

Since Mar 28Pushed 9y ago1 watchersCompare

[ Source](https://github.com/quankim/cakephp-jwt-auth)[ Packagist](https://packagist.org/packages/quankim/cakephp-jwt-auth)[ RSS](/packages/quankim-cakephp-jwt-auth/feed)WikiDiscussions master Synced 2mo ago

READMEChangelog (2)Dependencies (2)Versions (3)Used By (1)

QuanKim/JwtAuth custom plugin for CakePHP
=========================================

[](#quankimjwtauth-custom-plugin-for-cakephp)

[![Build Status](https://camo.githubusercontent.com/1b515a387343910324b2eea008345d671e06c8a58c125643cfd95dcf10f2f374/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f5175616e4b696d2f63616b657068702d6a77742d617574682f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/QuanKim/cakephp-jwt-auth)[![Coverage](https://camo.githubusercontent.com/eb799846413771ec0dc8c14c1b6f7ee8ae1b7bbf38a6e6a3ceaac03d9c89d4e2/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f5175616e4b696d2f63616b657068702d6a77742d617574682e7376673f7374796c653d666c61742d737175617265)](https://codecov.io/github/QuanKim/cakephp-jwt-auth)[![Total Downloads](https://camo.githubusercontent.com/394814f93aa70b3ebf920ac5c133f571dde5f18f8c29694ac10507ad77fb1a84/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f5175616e4b696d2f63616b657068702d6a77742d617574682e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/QuanKim/cakephp-jwt-auth)[![License](https://camo.githubusercontent.com/942e017bf0672002dd32a857c95d66f28c5900ab541838c6c664442516309c8a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e7376673f7374796c653d666c61742d737175617265)](LICENSE.txt)

Installation
------------

[](#installation)

You can install this plugin into your CakePHP application using [composer](http://getcomposer.org).

The recommended way to install composer packages is:

```
composer require quankim/cakephp-jwt-auth

```

Usage
-----

[](#usage)

In your app's `config/bootstrap.php` add:

```
// In config/bootstrap.php
Plugin::load('QuanKim/JwtAuth');
```

or using cake's console:

```
./bin/cake plugin load QuanKim/JwtAuth
```

Migrate AuthToken table:

```
./bin/cake migrations migrate -p QuanKim/JwtAuth
```

Configuration:
--------------

[](#configuration)

Setup `AuthComponent`:

```
    // In your controller, for e.g. src/Api/AppController.php
    public function initialize()
    {
        parent::initialize();

        $this->loadComponent('Auth', [
            'storage' => 'Memory',
            'authenticate', [
                'QuanKim/JwtAuth.Jwt' => [
                    'userModel' => 'Users',
                    'fields' => [
                        'username' => 'id'
                    ],

                    'parameter' => 'token',

                    // Boolean indicating whether the "sub" claim of JWT payload
                    // should be used to query the Users model and get user info.
                    // If set to `false` JWT's payload is directly returned.
                    'queryDatasource' => true,
                ]
            ],

            'unauthorizedRedirect' => false,
            'checkAuthIn' => 'Controller.initialize',

            // If you don't have a login action in your application set
            // 'loginAction' to false to prevent getting a MissingRouteException.
            'loginAction' => false
        ]);
    }
```

Setup `Config/app.php`Add in bottom of file:

```
'AuthToken'=>[
        'expire'=>3600
    ]
```

Working
-------

[](#working)

The authentication class checks for the token in two locations:

- `HTTP_AUTHORIZATION` environment variable:

    It first checks if token is passed using `Authorization` request header. The value should be of form `Bearer `. The `Authorization` header name and token prefix `Bearer` can be customzied using options `header` and `prefix`respectively.

    **Note:** Some servers don't populate `$_SERVER['HTTP_AUTHORIZATION']` when `Authorization` header is set. So it's upto you to ensure that either `$_SERVER['HTTP_AUTHORIZATION']` or `$_ENV['HTTP_AUTHORIZATION']` is set.

    For e.g. for apache you could use the following:

    ```
    RewriteEngine On
    RewriteCond %{HTTP:Authorization} ^(.*)
    RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

    ```
- The query string variable specified using `parameter` config:

    Next it checks if the token is present in query string. The default variable name is `token` and can be customzied by using the `parameter` config shown above.

Token Generation
----------------

[](#token-generation)

You can use `\Firebase\JWT\JWT::encode()` of the [firebase/php-jwt](https://github.com/firebase/php-jwt)lib, which this plugin depends on, to generate tokens.

**The payload should have the "sub" (subject) claim whos value is used to query the Users model and find record matching the "id" field.**

Example:

```
$access_token = JWT::encode([
                'sub' => $user['id'],
                'exp' =>  time() + $expire
            ],Security::salt());
$refresh_token = JWT::encode([
                'sub' => $user['id'],
                'ref'=>time()
            ],Security::salt());
$authToken = $this->Users->AuthToken->newEntity();
$authToken->user_id = $user['id'];
$authToken->access_token = $access_token;
$authToken->refresh_token = $refresh_token;
$this->Users->AuthToken->save($authToken);
$this->set([
    'success' => true,
    'data' => [
        'access_token' => $access_token,
        'refresh_token'=> $refresh_token,
        'id'=>$user['id'],
        'username'=> $user['username'],
        'email'=> $user['email']
    ],
    '_serialize' => ['success', 'data']
]);
```

You can set the `queryDatasource` option to `false` to directly return the token's payload as user info without querying datasource for matching user record.

Further reading
---------------

[](#further-reading)

For an end to end usage example check out [this](http://www.bravo-kernel.com/2015/04/how-to-add-jwt-authentication-to-a-cakephp-3-rest-api/) blog post by Bravo Kernel.

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~97 days

Total

2

Last Release

3602d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/13218211?v=4)[Mr.Don't Ask](/maintainers/quanvh)[@quanvh](https://github.com/quanvh)

---

Top Contributors

[![quankim277](https://avatars.githubusercontent.com/u/16264515?v=4)](https://github.com/quankim277 "quankim277 (1 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/quankim-cakephp-jwt-auth/health.svg)

```
[![Health](https://phpackages.com/badges/quankim-cakephp-jwt-auth/health.svg)](https://phpackages.com/packages/quankim-cakephp-jwt-auth)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
