Export (0) Print
Expand All

Monitoring Authentication State (JavaScript Library)

Ff748098.note(en-us,MSDN.10).gifNote:
Current information about Live Connect is now available in the Windows Live Developer Center. The information in the following sections is provided for legacy purposes only.

This topic demonstrates how to monitor the authentication state of the currently signed-in user. To do this, you register an event listener for the propertyChanged event and create an event handler function to process the resulting data each time the event is raised. The propertyChanged event is raised only for the following Auth properties:

The following code example shows how to register an event listener for the Auth.propertyChanged event. This registration can be done at application load time, as shown.

function appOnload() {
    app = Microsoft.Live.App;

    // Get the Auth instance.
    auth = app.get_auth();

    // Register an event listener for the propertyChanged event,
    // passing the event handler method name as the value.
    auth.add_propertyChanged(onAuthStateChange);
    handleStateChange(auth);

To work with the data that is returned each time there is a change in the authentication state or in any other supported property of the Auth class, you set up an event-handler function as shown in the following code example.

function onAuthStateChange(sender, e) {
    var auth = Type.safeCast(sender, Microsoft.Live.Auth);
    if (Sys.isNullOrUndefined(auth)) {
        Sys.Debug.trace("onAuthStateChange: auth is null or undefined (ignoring state change)");
        return;
    }

    if (e.get_propertyName() != 'state') {
        Sys.Debug.trace("onAuthStateChange: property is '" + e.get_propertyName() + "' (ignoring state change)");
        return;
    }

    handleStateChange(auth);
}

In the preceding example, the auth variable is created by using the sender parameter, and is cast to the Microsoft.Live.Auth type by using the Type.method. If the auth value is null or undefined, or if the property is a non-state property, a trace message is logged and the function returns. Otherwise the auth state is changed, and the showProperties function is called.

A separate function is used to handle the auth.state property changes, as shown in the following code example.

function handleStateChange(auth) {
    var authState = auth.get_state();
    Sys.Debug.trace("onAuthStateChange: state changed to " + authState);
    var app = Microsoft.Live.App;

    var t = $get('properties');
    if (t) {
        t.parentNode.removeChild(t);
    }

    t = document.createElement("table");
    var tbody = document.createElement("tbody");
    t.appendChild(tbody);
    t.setAttribute('id', "properties");

    if (authState == 0) {
        // Consent failed.
        Sys.Debug.trace('handleStateChange: Microsoft.Live.AuthState.unauthenticated');
        if (!String.isNullOrEmpty(auth.get_errorMsg())) {
            Sys.Debug.trace('Error ' + auth.get_errorMsg());
        }
        // Display because the user may have valid scopes from a previous request.
        displayScopes();
    }

    else if (authState == 3) {
        // Consent failed.
        Sys.Debug.trace('handleStateChange: Microsoft.Live.AuthState.failed');
        if (!String.isNullOrEmpty(auth.get_errorMsg())) {
            Sys.Debug.trace('Error ' + auth.get_errorMsg());
        }
        // Display because the user may have valid scopes from a previous request.
        displayScopes();
    }
    else if (authState == 4) {
        // Consent success.
        Sys.Debug.trace('handleStateChange: Microsoft.Live.AuthState.authenticated');
        Sys.Debug.trace('CID: ' + auth.get_cid());
        Sys.Debug.trace('wrap_clientstate: ' + app.get_clientState());
        Sys.Debug.trace('scope namespace: ' + auth.get_scopeNamespace());

        var accessToken = auth.get_accessToken();
        if (!String.isNullOrEmpty(accessToken)) {
            Sys.Debug.trace('Access token: ' + accessToken);
        }

        displayScopes();
    }
}

function displayScopes() {
    var auth = Microsoft.Live.App.get_auth();
    if (auth.get_grantedScopes() == null) {
        return;
    }

    var i;
    for (i = 0; i < auth.get_grantedScopes().length; i++) {
        Sys.Debug.trace('Granted: ' + auth.get_grantedScopes()[i] + ', expires ' + auth.get_expirationDates()[i]);
    }
    for (i = 0; i < auth.get_requestedScopes().length; i++) {
        Sys.Debug.trace('Requested: ' + auth.get_requestedScopes()[i]);
    }
}

Ff748098.note(en-us,MSDN.10).gifTip:
The Sys.Debug.trace function provides a way to observe the sequence of events that occurs throughout the life cycle of the page. For more information, see Debugging and Tracing AJAX Applications Overview.

The following sample puts all of the example code for this topic together in a webpage. To test this page:

  1. Follow the instructions in Getting Started Sample for ASP.NET.
  2. Create a new ASPX page in the sample project.
  3. Replace the HTML element with the code shown after this procedure.
  4. Update the code by providing your client ID in the <wl:app> tag.
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:wl="http://apis.live.net/js/2010">
<head runat="server">
    <title>How To Monitor Authentication State</title>
    <script type="text/javascript" src="http://js.live.net/4.1/loader.js"></script>
    <script type="text/javascript">
        var app;
        var auth;
        function appOnload() {
            app = Microsoft.Live.App;

            // Get the Auth instance.
            auth = app.get_auth();

            // Register an event listener for the propertyChanged event,
            // passing the event handler method name as the value.
            auth.add_propertyChanged(onAuthStateChange);
            handleStateChange(auth);

        function onSignin() {
            // Set the client state value.
            var clientstate = $get('clientstate').value;
            if ((clientstate != null) && (clientstate != "")) {
                app.set_clientState(clientstate);
            }
        }

        // The propertyChanged event handler function.
        function onAuthStateChange(sender, e) {
            var auth = Type.safeCast(sender, Microsoft.Live.Auth);
            if (Sys.isNullOrUndefined(auth)) {
                Sys.Debug.trace("onAuthStateChange: auth is null or undefined (ignoring state change)");
                return;
            }

            if (e.get_propertyName() != 'state') {
                Sys.Debug.trace("onAuthStateChange: property is '" + e.get_propertyName() + "' (ignoring state change)");
                return;
            }

            handleStateChange(auth);
        }

        // Log state changes to trace.
        function handleStateChange(auth) {
            var authState = auth.get_state();
            Sys.Debug.trace("onAuthStateChange: state changed to " + authState);
            var app = Microsoft.Live.App;

            var t = $get('properties');
            if (t) {
                t.parentNode.removeChild(t);
            }

            t = document.createElement("table");
            var tbody = document.createElement("tbody");
            t.appendChild(tbody);
            t.setAttribute('id', "properties");

            if (authState == 0) {
                // Consent failed.
                Sys.Debug.trace('handleStateChange: Microsoft.Live.AuthState.unauthenticated');
                if (!String.isNullOrEmpty(auth.get_errorMsg())) {
                    Sys.Debug.trace('Error ' + auth.get_errorMsg());
                }
                // Display because the user may have valid scopes from a previous request.
                displayScopes();
            }

            else if (authState == 3) {
                // Consent failed.
                Sys.Debug.trace('handleStateChange: Microsoft.Live.AuthState.failed');
                if (!String.isNullOrEmpty(auth.get_errorMsg())) {
                    Sys.Debug.trace('Error ' + auth.get_errorMsg());
                }
                // Display because the user may have valid scopes from a previous request.
                displayScopes();
            }
            else if (authState == 4) {
                // Consent success.
                Sys.Debug.trace('handleStateChange: Microsoft.Live.AuthState.authenticated');
                Sys.Debug.trace('CID: ' + auth.get_cid());
                Sys.Debug.trace('wrap_clientstate: ' + app.get_clientState());
                Sys.Debug.trace('scope namespace: ' + auth.get_scopeNamespace());

                var accessToken = auth.get_accessToken();
                if (!String.isNullOrEmpty(accessToken)) {
                    Sys.Debug.trace('Access token: ' + accessToken);
                }

                displayScopes();
            }
        }

        function displayScopes() {
            var auth = Microsoft.Live.App.get_auth();
            if (auth.get_grantedScopes() == null) {
                return;
            }

            var i;
            for (i = 0; i < auth.get_grantedScopes().length; i++) {
                Sys.Debug.trace('Granted: ' + auth.get_grantedScopes()[i] + ', expires ' + auth.get_expirationDates()[i]);
            }
            for (i = 0; i < auth.get_requestedScopes().length; i++) {
                Sys.Debug.trace('Requested: ' + auth.get_requestedScopes()[i]);
            }
        }
        </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>How To Monitor Authentication State</h1> 
        <p>This sample demonstrates how to monitor authentication state changes by using the <b>propertyChanged</b> event. Enter a client state string and then sign in. All the state-change events are traced, and you can see them in the &lt;textarea&gt; element at the bottom of the page.</p>
        Client State string: <input id="clientstate" type="text" name="clientstate" /><br /><br />     
        <wl:signin theme="white" onsignin="{{onSignin}}"></wl:signin>        
    </div>
    <br />

    <wl:app
        channel-url="/channel.htm"
        callback-url="/OAuthWrapCallback.ashx?wl_session_id=<%= Session.SessionID %>"
        client-id="<Your-Client-Id>"
        scope="WL_Contacts.View"
        onload="appOnload">
    </wl:app>

    <div style="position: fixed; bottom: 0px; left: 0px; right: 0px;">
        <textarea id="TraceConsole" rows="25" cols="100" style="width: 99%"></textarea>
    </div>
    </form>
</body>
</html>

Show:
© 2015 Microsoft