Can't destroy AWS Cognito session from within React application
Asked Answered
A

2

6

I'm trying to log out of my application that's using AWS Cognito by calling their logout endpoint. I'm not using the AWS SDK because as far as I can tell, it does not yet cover oauth app integrations and sign in using external federated identity providers (please correct me if I'm wrong about that). I log in from an AWS-hosted login screen that I'm redirected to when I call their authorization endpoint. They redirect me back to my page with a "code" which I post back to them using their token endpoint to get tokens. All of this is textbook oauth 2.0 stuff.

The problem is that when I call the logout endpoint using a JavaScript browser redirect (window.location.href = ....) it doesn't clear the cookies that are set when I logged in ("XSRF-TOKEN" and "cognito") and I can't manually clear them because they were set from the AWS domain which is different from the one where my site is hosted. The cookies do get cleared when I enter the logout link in the address bar. There's clearly a difference between using window.location.href in code and dropping a link in my address bar.

Abstractionism answered 15/3, 2018 at 21:59 Comment(1)
Can you add your code?Flowerdeluce
R
1

To clear out the sessoin you need to use clearCachecId() and then reset the Cognito Id credentials. This is my function using the 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
  }      
}

That should take care of that.

Rothko answered 16/3, 2018 at 17:44 Comment(1)
The clearCachedId() is exactly what I needed. Thank you.Withal
A
0

It's a timing issue involving the use of windows.location and cookies. It seems that I was causing the same cookie, XSRF-TOKEN, to be unset and then reset so fast that it was just not happening at all. Inserting a timeout between logging out and redirecting back to the log in screen fixes the problem. There are some guys on this thread who seem to know something about it: https://bytes.com/topic/javascript/answers/90960-window-location-cookies

Abstractionism answered 20/3, 2018 at 1:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.