无法从React应用程序中销毁AWS Cognito会话

时间:2018-03-15 21:59:16

标签: javascript reactjs amazon-cognito aws-cognito window.location

我试图通过调用他们的注销endpoint来退出使用AWS Cognito的应用程序。我没有使用AWS SDK,因为据我所知,它还没有涵盖oauth app集成并使用外部联合身份提供商登录(如果我错了,请纠正我)。我从AWS托管的登录屏幕登录,当我拨打他们的授权endpoint时,我将其重定向到该屏幕。他们使用"代码"将我重定向回我的页面。我使用他们的令牌endpoint发回给他们来获取令牌。所有这些都是教科书oauth 2.0的东西。

问题在于,当我使用JavaScript浏览器重定向(window.location.href = ....)调用注销端点时,它不会清除我登录时设置的cookie(&#34) ; XSRF-TOKEN"以及#34; cognito")我无法手动清除它们,因为它们是从AWS域设置的,这与我的站点所在的域不同。当我在地址栏中输入注销链接时,cookie会被清除。在代码中使用window.location.href和在地址栏中删除链接显然有区别。

2 个答案:

答案 0 :(得分:0)

要清除sessoin,您需要使用clearCachecId(),然后重置Cognito Id凭据。这是我使用AWS SDK的功能:

import AWS from 'aws-sdk/global';

const getCurrentUser = () => {
  const userPool = newCognitoUserPool({
    UserPoolId: YOUR_USER_POOL_ID,
    ClientId: YOUR_APP_CLIENT_ID
  });
  return userPool.getCurrentUser();
}

const signOutUser = () => {
  const currentUser = getCurrentUser();

  if (currentUser !== null) {
    curentUser.signOut();
  }

  if (AWS.config.credentials) {
    AWS.config.credentials.clearCachedId(); // this is the clear session
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({}); // this is the new instance after the clear
  }      
}

那应该照顾好。

答案 1 :(得分:0)

这是一个涉及使用windows.location和cookies的计时问题。似乎我导致相同的cookie,XSRF-TOKEN被取消,然后重置得如此之快,以至于根本没有发生。在注销和重定向回登录屏幕之间插入超时可以解决问题。这个帖子中有些人似乎对此有所了解:https://bytes.com/topic/javascript/answers/90960-window-location-cookies