1

作为带有 url 前缀的签名 url的替代方法,我正在尝试让签名的 cookie工作。Google Cloud CDN 设置了一个后端存储桶,该存储桶已配置并适用于标准签名 URL。

使用这些Go 示例,我在 nodejs(typescript) 中实现了一个 cookie 签名功能,当提供测试样本数据时,它会产生预期的结果。

export function signCookie(urlPrefix: any, keyName: string, key: any, experation: Date): string {
    // Base64url encode the url prefix
    const urlPrefixEncoded = Buffer.from(urlPrefix)
        .toString('base64')
        .replace(/\+/g, '-')
        .replace(/\//g, '_');

    // Input to be signed
    const input = `URLPrefix=${urlPrefixEncoded}:Expires=${experation.getTime()}:KeyName=${keyName}`;

    // Create bytes from given key string.
    const keyBytes = Buffer.from(key, 'base64');

    // Use key bytes and crypto.createHmac to produce a base64 encoded signature which is then escaped to be base64url encoded.
    const signature = createHmac('sha1', keyBytes)
        .update(input)
        .digest('base64').replace(/\+/g, '-')
        .replace(/\//g, '_');

    // Adding the signature on the end if the cookie value
    const signedValue = `${input}:Signature=${signature}`;

    return signedValue;
}

然后,当我使用相同的函数为我的实际 cdn 实例生成签名 cookie 值时,我得到以下信息(键名和 url 前缀不是实际的):

URLPrefix=aHR0cHM6L---HdhcmUuaW8v:Expires=1587585646437:KeyName=my-key-name:Signature=2mJbbtYVclycXBGIpKzsJWuLXEA=

使用 firefox 开发工具创建烹饪我在附加 cookie 和未附加 cookie 时得到以下两个结果:

附上签名的 Cookie 没有签名的 cookie

似乎 cookie“Cloud-CDN-Cookie”只是通过 Cloud CDN 传递并直接传递到后端存储桶,在那里它被忽略并给出了标准响应访问拒绝响应。

云平台日志显示没有cdn干预。

附上 cookie 未附上附上 cookie cookie 没有附加cookie

在签名实施或创建和使用 cookie 中我做错了什么吗?

4

1 回答 1

1

我的 Google 项目还没有启用签名 cookie 功能。另一位用户联系了支持人员,一旦为他们解决了问题,对我来说就解决了,无需更改代码并且可以正常工作。

这是我最终的 nodejs(typescript) 签名 cookie 实现。

function signCookie(urlPrefix: any, keyName: string, key: any, experation: Date): string {
    // Base64url encode the url prefix
    const urlPrefixEncoded = Buffer.from(urlPrefix)
        .toString('base64')
        .replace(/\+/g, '-')
        .replace(/\//g, '_');

    // Input to be signed
    const input = `URLPrefix=${urlPrefixEncoded}:Expires=${experation.getTime()}:KeyName=${keyName}`;

    // Create bytes from given key string.
    const keyBytes = Buffer.from(key, 'base64');

    // Use key bytes and crypto.createHmac to produce a base64 encoded signature which is then escaped to be base64url encoded.
    const signature = createHmac('sha1', keyBytes)
        .update(input)
        .digest('base64').replace(/\+/g, '-')
        .replace(/\//g, '_');

    // Adding the signature on the end if the cookie value
    const signedValue = `${input}:Signature=${signature}`;

    return signedValue;
}
于 2020-04-25T13:50:27.087 回答