sam-it/yii2-urlsigner

为 Yii2 框架提供安全的 URL 签名和验证

安装次数: 24,257

依赖者: 0

建议者: 0

安全: 0

星标: 6

关注者: 1

分支: 3

开放问题: 0

类型:yii2-extension

v2.0.0 2018-10-08 15:05 UTC

This package is auto-updated.

Last update: 2024-08-25 21:47:10 UTC


README

Scrutinizer Code Quality Code Coverage Build Status

yii2-urlsigner 安全的 URL 签名和验证。

此组件的目标是实现无状态的但安全的 URL 验证。例如,在进行电子邮件验证或密码重置时,这可能很有用。

想法很简单,考虑我想更改我的电子邮件,系统可以发送给我这样的链接

当然,这非常不安全,没有人(希望)会这样做。一个解决方案是生成一个随机的令牌

这是安全的,但需要在服务器上保持状态。此软件包通过签名 URL 解决了这个问题

这允许我们验证该 URL 是否确实是由我们创建的,因此可以信任。

示例

class RequestResetAction {

    public function run(
        UrlSigner $urlSigner,
        int $id,
        string $email
    ) {
        $user = User::find()->andWhere([
            'id' => $id,
            'email' => $email
        ]);

        $route = [
            '/user/do-reset',
            'id' => $user->id,
            'crc' => crc32($user->password_hash),
        ];

        /**
         * Sign the params.
         * 1st param is passed by reference, the component adds the params needed for HMAC.
         * 2nd param indicates that the params must match exactly, the user cannot add another param.
         * 3rd param sets the expiration to 1 hour
         **/
        $urlSigner->signParams($route, false, (new DateTime())->add(new DateInterval('PT1H')));

        $user->sendPasswordReset($route);



    }
}

class DoResetAction {

    public function behaviors()
    {
        return [
            'hmacFilter' => [
            'class' => HmacFilter::class,
            'signer' => $this->controller->module->get('urlSigner'),
        ];

    }
    public function run(
        int $id
    ) {
        // Here we can trust that the user got here through the link that we sent.



    }
}

不要在主机之间共享机密

如果您在多主机应用程序中使用此组件,您必须确保每个主机使用不同的密钥。URL 签名会考虑绝对路由和所有给定参数,任何其他内容都不会包含在签名和验证中。这意味着如果您有如下结构

并且他们使用相同的路由,例如 /user/do-reset 用于密码重置,普通用户将能够更改域名而不会使签名无效。