Our MSAL.js sample is an excellent example for using MSAL in a javascript page. However, it only demonstrates logging in by clicking on a button. If you’re launching your app from myapps portal or are otherwise already logged into the portal with the browser, it would make sense to just use that session to perform your sign-in for your MSAL app without requiring the button click.

This is actually easily done. Using the VanillaJSTestApp in the Samples folder of the repository, I made a simple code change to do this. First thing you need is to get an event listener setup for the Page load event. In the sample project, I did this by simply adding the following code in the Head:

<head>
    <title>Quickstart for MSAL JS</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js"></script>
    <script type="text/javascript" src="https://alcdn.msauth.net/lib/1.1.3/js/msal.js" integrity="sha384-m/3NDUcz4krpIIiHgpeO0O8uxSghb+lfBTngquAo2Zuy2fEF+YgFeP08PWFo5FiJ" crossorigin="anonymous"></script>
    <script type="text/javascript">
        if (typeof Msal === 'undefined') document.write(unescape("%3Cscript src='https://alcdn.msftauth.net/lib/1.1.3/js/msal.js' type='text/javascript' integrity='sha384-m/3NDUcz4krpIIiHgpeO0O8uxSghb+lfBTngquAo2Zuy2fEF+YgFeP08PWFo5FiJ' crossorigin='anonymous'%3E%3C/script%3E"));
        window.addEventListener("load", function () {
            console.log("onLoad");
            autoSignIn();
        });
    </script>
</head>

Next, I created my own method called “autoSignIn()” and for the most part, I just copied the “signIn” method and tweaked it a bit. First, I didn’t want the popup to occur which, when using the loginPopup method would flash a window. Instead, I chose to do the loginRedirect method. That would not show the popup unless you are not actualy signed in. However, as part of that flow, after successfully signing in, you would be redirected to the path that you have configured to redirect and so you must have your redirect handler in place, which the sample does and it is called “authRedirectCallBack”.

So, my sample code for the autoSignIn method looks like this:

function autoSignIn() {
    if (myMSALObj.getAccount() == null) {
        myMSALObj.loginRedirect(loginRequest).then(function (loginResponse) {
            showWelcomeMessage();
            myMSALObj.acquireTokenSilent(tokenRequest).then(function (tokenResponse) {
              callMSGraph(graphConfig.graphMeEndpoint, tokenResponse.accessToken, graphAPICallback);
            });
        });
    }
}

And that is it. This would cause the sample project to automatically sign-in if you’re already authenticated to Azure in another session.

0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments