LA.NET [EN]

Nov 22

[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!

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>