代码之家  ›  专栏  ›  技术社区  ›  Abd Abughazaleh

canI如何生成jwt-php令牌发送和修改令牌并检查validate

  •  0
  • Abd Abughazaleh  · 技术社区  · 6 年前

    我正试图使用这个库生成PHP令牌, https://github.com/lcobucci/jwt/blob/3.2/README.md ,我执行了以下代码:

    $signer = new Sha256();
    
    $token = (new Builder())->setIssuer('http://example.com') // Configures the issuer (iss claim)
                            ->setAudience('http://example.org') // Configures the audience (aud claim)
                            ->setId('4f1g23a12aa', true) // Configures the id (jti claim), replicating as a header item
                            ->setIssuedAt(time()) // Configures the time that the token was issue (iat claim)
                            ->setNotBefore(time() + 60) // Configures the time that the token can be used (nbf claim)
                            ->setExpiration(time() + 3600) // Configures the expiration time of the token (exp claim)
                            ->set('uid', 1) // Configures a new claim, called "uid"
                            ->sign($signer, 'testing') // creates a signature using "testing" as key
                            ->getToken(); // Retrieves the generated token
    

    如何检查此标志是否随附请求:- >sign($signer, 'testing')

    var_dump($token->verify($signer, 'testing 1')); // false, because the key is different
    var_dump($token->verify($signer, 'testing')); // true, because the key is the same
    

    此函数用于检查签名是否正确,但是,我需要使用来自请求的签名检查令牌。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Abd Abughazaleh    6 年前

    我用这个库解决了这个问题:

    https://github.com/firebase/php-jwt

    生成新令牌:

    $key = "example_key";
    $token = array(
        "iss" => "http://example.org",
        "aud" => "http://example.com",
        "iat" => 1356999524,
        "nbf" => 1357000000
    );
    
    /**
     * IMPORTANT:
     * You must specify supported algorithms for your application. See
     * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
     * for a list of spec-compliant algorithms.
     */
    $jwt = JWT::encode($token, $key); 
    $decoded = JWT::decode($jwt, $key, array('HS256'));
    
    print_r($decoded);
    

    $jwt=jwt::encode($token,$key);//这个用来用密钥($key=“example_key”;)生成新的令牌

    要输出令牌,请使用此行:

    echo $jwt ;
    

    若要检查此令牌是否登录您的密钥,请使用此。

    $decoded = JWT::decode($coming_token , $key, array('HS256'));