PHP code example of quankim / cakephp-jwt-auth

1. Go to this page and download the library: Download quankim/cakephp-jwt-auth library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

quankim / cakephp-jwt-auth example snippets


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

    // 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
        ]);
    }

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

$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']
]);