gamegos/jws

Json Web Signature (JWS) PHP实现

1.0.1 2015-04-09 08:33 UTC

This package is not auto-updated.

Last update: 2024-09-24 07:32:38 UTC


README

基于JWS草案的简单且可扩展的JWS PHP实现](http://tools.ietf.org/html/draft-ietf-jose-json-web-signature).

注意

gamegos/jwt库更适合JSON WEB TOKEN (JWT)解决方案

安装

推荐通过Composer安装gamegos/jws。

{
    "require": {
        "gamegos/jws": "~1.0"
    }
}

基本用法

编码

$headers = array(
    'alg' => 'HS256', //alg is required. see *Algorithms* section for supported algorithms
    'typ' => 'JWT'
);

// anything that json serializable
$payload = array(
    'sub' => 'someone@example.com',
    'iat' => '1402993531'
);

$key = 'some-secret-for-hmac';

$jws = new \Gamegos\JWS\JWS();
echo $jws->encode($headers, $payload, $key);
//eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzb21lb25lQGV4YW1wbGUuY29tIiwiaWF0IjoiMTQwMjk5MzUzMSJ9.0lgcQRnj_Jour8MLdIc71hPjjLVcQAOtagKVD9soaqU

解码与验证

$key = 'some-secret-for-hmac';

//jws encoded string
$jwsString = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzb21lb25lQGV4YW1wbGUuY29tIiwiaWF0IjoiMTQwMjk5MzUzMSJ9.0lgcQRnj_Jour8MLdIc71hPjjLVcQAOtagKVD9soaqU';

$jws = new \Gamegos\JWS\JWS();

$jws->verify($jwsString, $key);

如果一切正常,您将获得包含'headers'和'payload'的数组。

/*
Array
(
    [headers] => Array
        (
            [alg] => HS256
            [typ] => JWT
        )

    [payload] => Array
        (
            [sub] => someone@example.com
            [iat] => 1402993531
        )

)
*/

如果发生错误,您将获得以下异常之一。

如果您只想解析不带签名验证的jws字符串,可以使用decode方法。

$jws->decode($jwsString);

支持算法

目前支持以下算法。

请参阅JWS密码学算法页面,以获取JWS定义的所有算法的完整列表。

异常

  • InvalidSignatureException
  • MalformedSignatureException
  • UnspecifiedAlgorithmException
  • UnsupportedAlgorithmException

扩展:添加新的签名/MAC算法

创建一个实现\Gamegos\JWS\Algorithm\AlgorithmInterface的算法类

//example NoneAlgorithm
class NoneAlgorithm implements \Gamegos\JWS\Algorithm\AlgorithmInterface
{

    public function sign($key, $data)
    {
        return '';
    }

    public function verify($key, $data, $signature)
    {
        return (string) $signature === '';
    }
}

注册您的类

//...
$jws = new \Gamegos\JWS\JWS();
$jws->registerAlgorithm('my-new-algorithm', new NoneAlgorithm());

现在您可以使用my-new-algorithm作为常规的'alg'参数。

已知限制

  • JWS JSON序列化不受支持。

1需要php openssl模块