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

编程入门 行业动态 更新时间:2024-10-06 19:25:21

尝试通过 Cloud CDN 访问 GCP 存储桶<a href=https://www.elefans.com/category/jswz/34/1771374.html style=内容时获取 `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
});

希望它能为您节省时间。

更多推荐

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

本文发布于:2024-05-30 12:29:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770498.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:内容   CDN   Cloud   signed   GCP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!