【问题标题】:Unable to fetch a valid error code when AWS Cognito authentication failsAWS Cognito 身份验证失败时无法获取有效的错误代码
【发布时间】:2020-04-15 10:59:02
【问题描述】:

我正在使用 AWS Cognito 使用用户池进行身份验证,并且我在 API 网关上配置了所有 API。我直接从 Angular 客户端点击 cognito,将 Cognito 返回的令牌存储在本地存储中,并在后续调用中使用它们。

但问题是,如果我从 Angular 发送的令牌已过期,则 Cognito 身份验证将失败,并且在这种情况下不会命中集成后端。结果,我在 Chrome 中收到 401 错误。

然而,有趣的是,我无法在传递给 Angular 的 HTTP 响应对象中使用这个 401 代码。 Angular 接收到默认的 0 代码,这似乎是从服务器(认知或后端)接收到的所有错误代码的情况。

我尝试四处探索,发现问题可能是因为网关在错误情况下未发送正确的 CORS 标头。我已阅读以下相关文档,但不幸的是我找不到解决问题的方法。

有人可以提出解决方案吗?

编辑:我还在某处读到这是一个已知的 AWS 问题。是这样吗?

【问题讨论】:

    标签: amazon-web-services authentication aws-api-gateway amazon-cognito http-status-code-401


    【解决方案1】:

    您可以在调用 API 网关之前管理 Cognito 会话。

    在下面的示例中,getSession 方法有一个回调,可以将任何错误消息打印到控制台并返回。

    ////// Cognito.js
    import {
      CognitoUserPool,
      CookieStorage
    } from 'amazon-cognito-identity-js'
    
    import config from '../config'
    
    const cookieSettings = {
      domain: '.xxxxxxxxxxx.com',
      secure: true
    }
    
    export default {
      cookieSettings,
      pool: new CognitoUserPool({
        UserPoolId: config.UserPoolId,
        ClientId: config.ClientId,
        Storage: new CookieStorage(cookieSettings)
      })
    }
    //////
    
    ////// actions.js
    import Cognito from './Cognito'
    
    export function fetchUser() {
    
      // get cognito user cookies
      const cognitoUser = Cognito.pool.getCurrentUser()
      if (cognitoUser != null) {
        // try to get session from cognito
        cognitoUser.getSession(function(err, session) {
          if (err) {
            console.log(err)
    
            return;
          }
    
          fetch('https://api-gateway-url', { 
            headers: {
              Authorization: 'Bearer ' + session.getAccessToken().getJwtToken(), 
            }
          })
          .then(response => response.json())
          .then(json => console.log(json))
        })
      }
    
    }
    
    
    

    【讨论】:

    • 我已经试过了。但是,我的 getSession() 似乎总是返回一个空值。即使我的应用程序运行良好并且我能够进行各种 API 调用,getSession() 仍然返回 null。有什么想法吗?
    • Cognito 需要参考凭证的存储。因此,如果您手动将其存储到本地存储,getSession() 可能无法访问它。尝试使用CookieStorage,就像我在上面所做的那样。如果它不起作用,请发布您正在尝试的代码。
    猜你喜欢
    • 2020-12-31
    • 2015-03-26
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    • 2018-05-08
    • 1970-01-01
    • 2018-01-29
    相关资源
    最近更新 更多