Making the AuthenticationService.get_isLoggedIn() work correctly

[Update: this will only happen if you don”t set up the web.config properly. You don”t need to do this – ie, call the RegisterStartupScript – if you add the <authenticationService enabled=”true” /> to the web.config file]

The ASP.NET AJAX platform has some client services which you can use from your client Javascript code to perform some interesting operations. One of those classes is the Sys.Services._AuthenticationService class. Most guys will use the class to authenticate a user without having to perform a postback (ie, they”ll simply call the login method over the “global” Sys.Services. AuthenticationService object that is inserted on the page).

The class has a method (get_isLoggedIn) which should be used for letting you know if the user is authenticated. Unfortunately, the method might not give you the correct answer in all the scenarios because it simply checks the value of the _authenticated field to return a response. Now, If you use the service to login, then everything will work out correctly if you don”t navigate to another page. If you do, things won”t work as expected because the field isn”t updated during page navigation. Here”s a small page that reproduces this:

page A:

System.Web.Security.FormsAuthentication.SetAuthCookie(“luis”, true);
Response.Redirect(“Default.aspx” );

The page creates the authentication cookie and performs a response.redirect. If you put the following code on the default.aspx page:

alert( Sys.Services.AuthenticationService.get_isLoggedIn() );
alert(“<%= this.User.Identity.IsAuthenticated.ToString() %>”) 

You”ll get “false, True”. What we need to do is to ensure that the _authenticated field is correctly filled during page navigation. Fortunately, we can do that rather easily by injecting a script from the server side, with code that looks like this:

protected override void OnLoad(EventArgs e)
{
     base.OnLoad(e);
     ScriptManager.RegisterStartupScript( this, this.GetType(),”authenticated”,
          String.Format(“Sys.Services.AuthenticationService._authenticated={0};”,
                                      this.User.Identity.IsAuthenticated ? “true” : “false” ),
          true );
}

If your page has UpdatePanels, then don”t forget that these rules still apply!

Advertisements

~ by Luis Abreu on November 22, 2007.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: