Search code examples
amazon-cognitoaws-amplify

Listen to user inactivity with AWS Amplify / Cognito


Given that you can set access, refresh and ID token expiration time through the Amazon Cognito Console. How can I listen for the token expiring, so that I can redirect the user back to the login page and show an informational message when that happens?

I noticed that Amplify has a Hub utility where you can add listeners, but I'm not sure what to listen for.

https://docs.amplify.aws/lib/utilities/hub/q/platform/js/#state-management


Solution

  • Did quite a bit of resarch and found out that using the Amplify util called Hub, you can listen to the refresh token expiring, as well as other authentication related events.

    https://docs.amplify.aws/lib/utilities/hub/q/platform/js/

    Here's an example of a hook making use of it, React style:

    export const useCognitoContextProvider = () => {
      const [context, setContext] = useState({ isSignedIn: false });
    
      useEffect(() => {
        const authListener = ({ channel, payload: { event } }) => {
          if (channel === 'auth') {
            switch (event) {
              case 'signIn':
                setContext(prevState => (prevState.isSignedIn ? prevState : { ...prevState, isSignedIn: true }));
                break;
              case 'tokenRefresh_failure':
                SignOutService.signOut();
                break;
            }
          }
        };
    
        Hub.listen('auth', authListener);
    
        return (): void => {
          Hub.remove('auth', authListener);
        };
      }, []);
    
      return context;
    };

    And usage:

    // CognitoContext.js
    
    export const CognitoContext = createContext({ isSignedIn: false });
    
    // App.js
    
    const cognitoContext = useCognitoContextProvider();
    
    <Provider store={store}>
      <CognitoContext.Provider value={cognitoContext}>
        <Routes />
      </CognitoContext.Provider>
     </Provider>