amazon-archives / amazon-cognito-auth-js

The Amazon Cognito Auth SDK for JavaScript simplifies adding sign-up, sign-in with user profile functionality to web apps.
Apache License 2.0
424 stars 232 forks source link

Is it possible to check for a valid session on every page load BEFORE the onLoad function? #97

Open chris-denglere opened 6 years ago

chris-denglere commented 6 years ago

I'm working on an app where I want to check for a valid session (redirect to a hosted UI if one doesn't exist) on every page load. The onLoad function fires after the DOM is rendered. I created a function and call it at the very end of the head element of the html page. I did this so that the user doesn't see any of the page before they are redirected to the hosted UI. Much of the page layout and elements are dependent on authentication and their authorization level(s).

The function definition is:

//called before DOM is rendered
authentication.checkUserAuthentication = function()
{
    // https://github.com/aws/amazon-cognito-auth-js/blob/master/src/CognitoAuth.js
    authentication.aws.auth = new AmazonCognitoIdentity.CognitoAuth(authentication.aws.authData);
    authentication.aws.auth.useCodeGrantFlow();

    //register callbacks
    authentication.aws.auth.userhandler = {
        onSuccess: function(result) {
            console.log('result ' + JSON.stringify(result));

            authentication.aws.authenticatedUser = authentication.aws.auth.getCurrentUser();
            console.log('user ' + authentication.aws.authenticatedUser + ' is logged in');
        },
        onFailure: function(err) {
            console.log('error: ' + err);
            alert("Error!");
        }
    };

    if (authentication.aws.auth.getCachedSession().isValid() === true) {
        //the user's cached session is valid, authentication is not needed
        authentication.aws.authenticatedUser = authentication.aws.auth.getCurrentUser();
        console.log('user ' + authentication.aws.authenticatedUser + ' is already logged in');
    } else {
        authentication.aws.auth.getSession();

        //var curUrl = window.location.href;
        //parses the response URL and stores the tokens in local storage
        //authentication.aws.auth.parseCognitoWebResponse(curUrl);

        //trim off the fragment in URL so the user can bookmark a clean URL
        //history.pushState("", document.title, window.location.pathname);
    }
}

The sign in redirect URI is the same as the target URI that the user goes to originally. I'm getting an endless redirect cycle. Does anyone have any ideas on this?

blepoutr commented 6 years ago

Hi chris

I am not using exactly the same as you, as I am using Implicit grant. But I guess this is not such a big deal related to your question.

I would think that the problem that your are experiencing is because you never call "authentication.aws.auth.parseCognitoWebResponse(curUrl);"

Actually, this function seems to me the way

If you don't call it, then aws auth through the getsession will not see anything in the local storage and continue to redirect etc ...

I hope it helps

ericdsouza commented 5 years ago

I think it's because the onSuccess is async. The callback URL is executing and running the getCachedSession().isValid() check before the session becomes valid. If you remove the "getSession" from the else statement (to stop the endless redirect) and add in a console.log in the else, you should see that the 'else' code is being executed before the onSuccess code

I'm running into a similar problem. To fix, I've added a check for 'code' in the URL parameters, which exists if it's callback (i have a custom function to get URL parameters, you can insert your favourite way to check)

    } else {
        if 'code' exists in URL query parameters
            // do nothing       
        else
            authentication.aws.auth.getSession();       
    }