【问题标题】:CloudFront responds with 413 after AWS Cognito redirectAWS Cognito 重定向后 CloudFront 以 413 响应
【发布时间】:2021-03-17 21:33:42
【问题描述】:

我有一个使用 Serverless NextJS 构建的 React 应用程序,并在 AWS CloudFront 后面提供服务。我还使用 AWS Cognito 对我们的用户进行身份验证。

在用户通过 AWS Cognito 成功进行身份验证后,他们将被重定向到我的 React 应用程序,并使用包含 OAuth 令牌的查询字符串(id_tokenaccess_tokenrefresh_tokenraw[id_token]raw[access_token]raw[refresh_token] , raw[expires_in], raw[token_type])。

查询字符串似乎只是大于 AWS CloudFront 的限制,并在下面抛出以下错误:

413 ERROR
The request could not be satisfied.

Bad request. We can't connect to the server for this app...

Generated by cloudfront (CloudFront)
Request ID: FlfDp8raw80pAFCvu3g7VEb_IRYbhHoHBkOEQxYyOTWMsNlRjTA7FQ==

许多其他用户 (see example) 之前也遇到过此错误。想知道:

  • 有什么解决方法吗?也许有办法配置 AWS Cognito 以减少默认情况下在查询字符串中传递的令牌数量?

  • 是否可以将 AWS CloudFront 配置为忽略对某些页面(而不是缓存主题)强制执行其默认限制?

  • 接下来有什么建议?我唯一能想到的是使用 AWS CloudFront。

【问题讨论】:

    标签: amazon-cognito amazon-cloudfront http-status-code-413


    【解决方案1】:

    在分析 AWS Cognito 发送到回调 URL 的查询字段后,我能够确定我的用例并非所有字段都是必需的。特别是 raw OAuth 令牌字段。

    有了这些信息,我通过编写“中间件”来拦截我的后端系统重定向到我的前端(位于 CloudFront 后面)并修剪掉我不需要完成身份验证的查询字符串字段,从而解决了这个问题。

    如果这可能会激发其他人遇到类似问题,这是我的中间件在我的后端系统中的样子 (Strapi):

    module.exports = (strapi) => {
      return {
        initialize() {
          strapi.app.use(async (ctx, next) => {
            await next();
    
            if (ctx.request.url.startsWith("/connect/cognito/callback?code=")) {
              // Parse URL (with OAuth query string) Strapi is redirecting to
              const location = ctx.response.header.location;
              const { protocol, host, pathname, query } = url.parse(location);
    
              // Parse OAuth query string and remove redundant (and bloated) `raw` fields
              const queryObject = qs.parse(query);
              const trimmedQueryObject = _.omit(queryObject, "raw");
    
              // Reconstruct original redirect Url with shortened query string params
              const newLocation = `${protocol}//${host}${pathname}?${qs.stringify(
                trimmedQueryObject
              )}`;
    
              ctx.redirect(newLocation);
            }
          });
        },
      };
    };
    
    

    【讨论】:

    • 我的用例与您完全相同。非常感谢这个 sn-p!
    猜你喜欢
    • 2023-03-29
    • 2021-06-02
    • 2020-06-21
    • 1970-01-01
    • 2020-04-15
    • 2018-06-27
    • 2023-03-10
    • 1970-01-01
    • 2016-12-08
    相关资源
    最近更新 更多