steffenbrand/non-static-php-jwt

此包的最新版本(v5.0.0)没有提供许可证信息。

php-jwt 的非静态包装器

v5.0.0 2018-08-24 13:50 UTC

This package is auto-updated.

Last update: 2024-08-29 04:31:42 UTC


README

non-static-php-jwt 是一个用于 firebase/php-jwt 的包装器,使其能够通过 phpspec/prophecy(或任何其他模拟库)在你的 phpunit 测试中轻松模拟。

安装

composer require steffenbrand/non-static-php-jwt

版本控制

版本将从 ^5.0 开始与 firebase/php-jwt 的发布版本匹配。
支持的 PHP 版本将是 ^7.1,因为此库使用了返回类型和类型提示。

使用方法

它只是 firebase/php-jwt 的包装器,所以用法几乎相同,只是你需要首先创建一个 \SteffenBrand\NonStaticPhpJwt\Jwt 实例。

编码和解码

$jwt = new \SteffenBrand\NonStaticPhpJwt\Jwt();

$key = 'example_key';
$token = [
    'iss' => 'http://example.org',
    'aud' => 'http://example.com',
    'iat' => 1356999524,
    'nbf' => 1357000000
];

$webToken = $jwt->encode($token, $key);
$decoded = $jwt->decode($webToken, $key, ['HS256']);

var_dump($decoded);
print_r((array) $decoded);

添加容错时间

你可以添加一个容错时间来处理签名服务器和验证服务器之间的时钟偏差。建议这个容错时间不应超过几分钟。

来源: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef

容错时间是解码方法的第四个参数,默认值为 0

$jwt->decode($jwt, $key, ['HS256'], $leeway = 60);

预测

此库的主要目标是允许你在 phpunit 测试中对 JWT 方法的输出进行预测。

<?php

declare(strict_types=1);

namespace SteffenBrand\NonStaticPhpJwt\Test;

use PHPUnit\Framework\TestCase;
use Prophecy\Prophecy\MethodProphecy;
use Prophecy\Prophecy\ObjectProphecy;
use SteffenBrand\NonStaticPhpJwt\Jwt;

class JwtTest extends TestCase
{
    /**
     * @var Jwt
     */
    private $jwt;

    protected function setUp()
    {
        parent::setUp();
        $this->jwt = $this->prophesize(Jwt::class);
    }

    public function getSut(): Dummy
    {
        return new Dummy($this->jwt->reveal());
    }

    public function testJwtEncodeCanBeProphecised(): void
    {
        $returnValue = 'string';
        $this->jwt->encode([], '')->shouldBeCalled()->willReturn($returnValue);

        $this->assertInstanceOf(ObjectProphecy::class, $this->jwt);
        $this->assertInstanceOf(MethodProphecy::class, $this->jwt->getMethodProphecies('encode')[0]);
        $this->assertEquals($returnValue, $this->getSut()->encode());
    }

    public function testJwtDecodeCanBeProphecised(): void
    {
        $returnValue = new \stdClass();
        $this->jwt->decode('', '')->shouldBeCalled()->willReturn($returnValue);

        $this->assertInstanceOf(ObjectProphecy::class, $this->jwt);
        $this->assertInstanceOf(MethodProphecy::class, $this->jwt->getMethodProphecies('decode')[0]);
        $this->assertEquals($returnValue, $this->getSut()->decode());
    }

    public function testJwtSignCanBeProphecised(): void
    {
        $returnValue = 'string';
        $this->jwt->sign('', '')->shouldBeCalled()->willReturn($returnValue);

        $this->assertInstanceOf(ObjectProphecy::class, $this->jwt);
        $this->assertInstanceOf(MethodProphecy::class, $this->jwt->getMethodProphecies('sign')[0]);
        $this->assertEquals($returnValue, $this->getSut()->sign());
    }
}