最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

尝试通过 Cloud CDN 访问 GCP 存储桶内容时获取 `signed

网站源码admin47浏览0评论

尝试通过 Cloud CDN 访问 GCP 存储桶内容时获取 `signed

尝试通过 Cloud CDN 访问 GCP 存储桶内容时获取 `signed

我正在使用签名 cookie,通过 Cloud CDN 访问存储在 GCP 存储桶中的一些受限文件。我正在使用以下功能对 cookie 进行签名:

signCookie(urlPrefix: string, keyName: string, key: string, expires: number) {
    // Base64url encode the url prefix
    const urlPrefixEncoded = Buffer.from(urlPrefix).toString('base64url');

    // Input to be signed
    const input = `URLPrefix=${urlPrefixEncoded}:Expires=${expires}: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('base64url');

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

    return signedValue;
  }

正在生成 cookie 并发送到 CDN,但它失败并显示状态 403,并出现以下消息:

Error: Forbidden
Your client does not have permission to get URL ********/sample.pdf from this server.

在检查时,负载均衡器记录,我得到这个

statusDetails: "signed_request_invalid_format"
。不幸的是,此消息不在 here 列出的错误消息列表中。谁能帮我指出这个问题,签名的 cookie 是否无效? cookie的生成逻辑有没有错误?

回答如下:

此答案适用于使用

express
作为服务器的人。
sign cookie
函数按预期生成 cookie,设置 cookie 时出现问题。当我们这样设置 cookie 时:

response.cookie('Cloud-CDN-Cookie', cookieValue, {
          httpOnly: true,
          expires: new Date(cookieExpiryTime),
});

cookie 值得到 URI 编码,结果是 URL 的所有保留字符,如

=
,被替换为
%3D
等等。正如文档中所声明的那样,这会破坏 cookie 结构:

URLPrefix=$BASE64URLECNODEDURLORPREFIX:Expires=$TIMESTAMP:KeyName=$KEYNAME:Signature=$BASE64URLENCODEDHMAC

要解决此问题,请在设置 cookie 时传递额外的编码功能:

response.cookie('Cloud-CDN-Cookie', cookieValue, {
          httpOnly: true,
          expires: new Date(cookieExpiryTime),
          encode: val => val
});

希望它能为您节省时间。

发布评论

评论列表(0)

  1. 暂无评论