爱意满满的作品展示区。
gaozihang

为了提高性能,用 PHP 扩展实现了一个 JWT (JSON Web Token)

  •  1
     
  •   gaozihang · May 24, 2018 · 7196 views
    This topic created in 2915 days ago, the information mentioned may be changed or developed.

    目前 PHP 所有的 JWT 库都是用 PHP 语言编写的,为了提高性能,我基于 openssl 库,用 PHP 扩展实现了一个 JWT

    GitHub: https://github.com/cdoco/php-jwt

    例子

    $key = "example-hmac-key";
    $claims = array(
        "data" => [
            "name" => "ZiHang Gao",
            "admin" => true
        ],
        "iss" => "http://example.org",
        "sub" => "1234567890",
    );
    
    // default HS256 algorithm
    $token = jwt_encode($claims, $key);
    
    echo $token . PHP_EOL;
    //eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.
    //eyJpc3MiOiJodHRwOlwvXC9leGFtcGxlLm9yZyIsInN1YiI6IjEyMzQ1Njc4OTAiLCJuYW1lIjoiWmlIYW5nIEdhbyIsImFkbWluIjp0cnVlfQ.
    //2lFeBTsRegsjXiBCZNkW41KFlsZPSFu7KTsyAM9lUiQ
    
    print_r(jwt_decode($token, $key));
    /**
    Array
    (
        [data] => Array
            (
                [name] => ZiHang Gao
                [admin] => 1
            )
    
        [iss] => http://example.org
        [sub] => 1234567890
    )
    */
    
    14 replies    2025-04-13 23:00:52 +08:00
    oott123
        1
    oott123  
       May 24, 2018
    怎么也得搞个 benchmark 让大家看看你的有多快啊,不然怎么吸引用户 233
    qloog
        2
    qloog  
       May 24, 2018
    能写出来就至少给个 666
    predator
        3
    predator  
       May 24, 2018
    赞一个,7+的暂时只能在测试环境体验下先
    gaozihang
        4
    gaozihang  
    OP
       May 24, 2018
    @oott123 我自己跑的 benchmark,是 PHP 的 5-6 倍,后续会把 benchmark 贴出来 ~
    wensonsmith
        5
    wensonsmith  
       May 24, 2018
    战略 Mark, 666
    yongjing
        6
    yongjing  
       May 24, 2018
    66666
    m939594960
        7
    m939594960  
       May 24, 2018
    好东西啊
    swordne
        8
    swordne  
       May 24, 2018
    star 一下。
    LeungJZ
        9
    LeungJZ  
       May 24, 2018 via iPhone
    战略性马克。
    习惯性 666。
    vibbow
        10
    vibbow  
       May 24, 2018
    其实并没有太大作用,单个请求周期里,JWT 运算占用的总运算时间非常之少,哪怕性能提升 1w 倍对整个请求的响应时间也不会有什么显著改进的。

    而且还会导致跨版本升级的时候还需要等你这个扩展支持新版本...

    目前耗时大头应该都是数据库操作...
    notreami
        11
    notreami  
       May 24, 2018
    还不如加个缓存
    changwei
        12
    changwei  
       May 25, 2018 via Android
    jwt 的加解密操作主要都是用 php 扩展提供的加解密和序列化函数操作的,php 扩展函数本身就是 c 写的,理论来说纯扩展和 php 库的速度差别应该不大啊。
    pushy
        13
    pushy  
       May 25, 2018
    你的业务性能消耗在 JWT 上?
    mrgirff
        14
    mrgirff  
       Apr 13, 2025
    推荐一个可以在线生成 JWT Key Generator https://jwtsecrets.com/tools
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3091 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 71ms · UTC 00:32 · PVG 08:32 · LAX 17:32 · JFK 20:32
    ♥ Do have faith in what you're doing.