038.CI4框架CodeIgniter,使用Jwt生成token

像一棵海草海草海草發表於2024-08-31

01、在composer.json中增加一行呼叫jwt的程式碼:

{
    "name": "codeigniter4/appstarter",
    "description": "CodeIgniter4 starter app",
    "license": "MIT",
    "type": "project",
    "homepage": "https://codeigniter.com",
    "support": {
        "forum": "https://forum.codeigniter.com/",
        "source": "https://github.com/codeigniter4/CodeIgniter4",
        "slack": "https://codeigniterchat.slack.com"
    },
    "require": {
        "php": "^8.1",
        "codeigniter4/framework": "^4.5.3",
        "firebase/php-jwt": "^5.2"
    },
    "require-dev": {
        "fakerphp/faker": "^1.9",
        "mikey179/vfsstream": "^1.6",
        "phpunit/phpunit": "^10.5.16"
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "exclude-from-classmap": [
            "**/Database/Migrations/**"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\Support\\": "tests/_support"
        }
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "scripts": {
        "test": "phpunit"
    }
}

02、在目錄中輸入composer update,就可以更新到最新的了。

03、Tx_jwt.php程式碼如下:

<?php

namespace App\Libraries;

use \Firebase\JWT\JWT;
use \Firebase\JWT\Key;

class Tx_jwt
{

    protected $key = '123abc';

    //http://localhost/phmci4/public/index.php/myjwt/generatejwt
    function encodeJWT($user)
    {
        $payload = array(
            'data' => $user,
            'iss' => 'TIANPAN',//簽發者 可以為空
            'aud' => 'TIANPAN',//面象的使用者,可以為空
            'iat' => time(),//簽發時間
            'nbf' => time(), //在什麼時候jwt開始生效  (這裡表示生成10秒後才生效)
            'exp' => time() + 3600, //token 過期時間
        );
        $jwt_encoded = JWT::encode($payload, $this->key);
        return $jwt_encoded;
    }

    //http://localhost/phmci4/public/index.php/myjwt/decodejwt
    function decodeJWT($token)
    {
        // 此時$decoded是一個物件,你可以根據需要訪問其屬性
        try {
            $jwt_decoded = JWT::decode($token, new Key($this->key, 'HS256'));
            return $jwt_decoded;
        } catch (\Exception $e) {
            return $e;
        }
    }

}

04、Api001.test程式碼如下;

<?php namespace App\Controllers\Api;

use App\Controllers\BaseController;
use App\Libraries\Tx_jwt;


//訪問地址:http://localhost/phmci4/public/index.php/api/api001/
class Api001 extends BaseController
{
    protected $Jwt;

    public function __construct()
    {
        $this->Jwt = new Tx_jwt;
    }

    //http://localhost/phmci4/public/index.php/api/api001/encodetoken
    public function encodetoken(): string
    {
        $user = array(
            'username' => 'tianpan',
            'role' => 'guest'
        );
        $token = $this->Jwt->encodeJWT($user);
        return $token;
    }

    //http://localhost/phmci4/public/index.php/api/api001/decodetoken
    public function decodetoken(): string
    {
        $token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7InVzZXJuYW1lIjoidGlhbnBhbiIsInJvbGUiOiJndWVzdCJ9LCJpc3MiOiJUSUFOUEFOIiwiYXVkIjoiVElBTlBBTiIsImlhdCI6MTcyNDk5NzczNCwibmJmIjoxNzI0OTk3NzM0LCJleHAiOjE3MjQ5OTc3NTR9.1Yr_4khWZYKa3IGXCJ4i0fpDCPr7RTyc21cNPclzR_k';
        $user = $this->Jwt->decodeJWT($token);
        return Json_encode($user);
    }
    //--------------------------------------------------------------------
}

05、結構目錄如下:

06、瀏覽器如下:

相關文章