簡體   English   中英

AWS Cognito 身份驗證失敗時無法獲取有效的錯誤代碼

[英]Unable to fetch a valid error code when AWS Cognito authentication fails

我使用 AWS Cognito 使用用戶池進行身份驗證,並且我在 API 網關上配置了所有 API。 我直接從 Angular 客戶端點擊 cognito,將 Cognito 返回的令牌存儲在本地存儲中,並在后續調用中使用它們。

然而,問題是,如果我從 Angular 發送的令牌已過期,Cognito 身份驗證將失敗,並且在這種情況下不會命中任何集成后端。 結果,我在 Chrome 中收到 401 錯誤。

然而有趣的是,這個 401 代碼在傳遞給 Angular 的 HTTP 響應對象中對我不可用。 Angular 收到默認的 0 代碼,從服務器(認知或后端)收到的所有錯誤代碼似乎都是這種情況。

我嘗試四處探索,發現問題可能是因為網關在錯誤情況下沒有發送正確的 CORS 標頭。 我已閱讀以下相關文檔,但不幸的是我找不到解決問題的方法。

有人可以為此提出解決方案。

編輯:我也在某處讀到這是一個已知的 AWS 問題。 是這樣嗎?

您可以在調用 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))
    })
  }

}


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM