1

The reason i need to do this is because of Facebook Connect - which is another story, so i'll save you the drama for that. =)

Anyway, i have this function that runs on window.onload:

function userAuth() {
   SomeFunctionWhichGetsFacebookCookes();
   if (!loggedInUsingFormsAuth && loggedInViaFacebook) {
     window.location.reload(); // refresh page, so i can perform auto-login
   }
}

So, i need help in getting the flag "loggedInUsingFormsAuth".

I dont care what is in the cookie, just need to know if the current user is authenticated.

Why am i doing this?

Well, on window load, if the user is logged into Facebook but not on my website (according to the Forms Authentication cookie), i want to reload the page - which allows my ASP.NET website to read the Facebook cookies in the HttpContext and log the user in. I need to do this in JavaScript, because i dont have the Facebook cookies until i call "SomeFunctionWhichGetsFacebookCookies" - which can only be done in JavaScript.

So, how can i work out if the current user is authenticated via JavaScript? Do i have to manually traverse through the cookies, find the one i want, and inspect it? Is this a safe thing to do?

Or should i alternatively write out the flag to the client from the server using RegisterClientScript?

1
  • Ended up registering the HttpContext.Current.Request.IsAuthenticated property to the client in order to be used by JavaScript. Easier. Commented Jul 20, 2010 at 5:32

4 Answers 4

4

You could add the following to your web.config file.

<system.web.extensions>
     <scripting>
    <webServices>
         <!-- Allows for ajax.net user authentication -->
         <authenticationService enabled="true" requireSSL="false" />
    </webServices>
     </scripting>
</system.web.extensions>

and then you are able to find out via javascript if you are authenticated like so.

function isAuth() {
    var result = Sys.Services.AuthenticationService.get_isLoggedIn();
    return result;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Interesting, but its still doing a call to the server behind the scenes.
0

A better way to do it than you have described inn your comment is to create a simple web service that you call to retrieve the value.

3 Comments

Then ill need an extra call to the server, which i dont want. I render out the javascript on Page_PreRender, now im just rendering it with the value from the server.
A call to the server is real time, checking a javascript variable will tell you the user is logged in when in fact their session has expired.
In theory, you're correct - but in fact im registering the javascript on page load, then checking the cookie immediately in the same javascript- in other words, in real time (page loads, check auth, set auth in javascript, javascript runs immediately and checks auth). Anyway thanks for the answer.
0

As i am registering the JavaScript via the server on every page load, i decided to set the HttpContext.Current.Request.IsAuthenticated property into the JavaScript itself.

In other words i had some JavaScript defined in the C# itself:

public class SomeClassWhichHasAccessToHttpContext
{
   private const string MyScript = "var foo='{0}'";

   public static string GetMyScript()
   {
      return string.Format(MyScript, HttpContext.Current.Request.IsAuthenticated);
   }
}

Then on the HTML for my main master page:

<%= SomeClassWhichHasAcccessToHttpContext.GetMyScript() =>

Normally i would not opt for a solution like this, i would normally call an asynchronous web service (as Ben's answer's mentions). But the fact is that this property and JavaScript is evaluated on a page-request basis, so the evaluation of this property will never be stale for each given HTTP Request.

Comments

0

I have a solution that only needs code in one place:

Add the code below to Global.asax.cs

    protected void Application_EndRequest(object sender, EventArgs e)
    {           
        try
        {
            System.Web.UI.Page P = (System.Web.UI.Page)HttpContext.Current.Handler;//will throw error if request is not for a page
            if (P.IsCallback) { return; }
            if (P.IsPostBack)
            {
                try
                {
                    //if using AjaxControlToolKit and UpdatePanels
                    if (AjaxControlToolkit.ToolkitScriptManager.GetCurrent(P).IsInAsyncPostBack)
                    {
                        //Async postback caused by update panel           
                        return;
                    }
                }
                catch (Exception)
                { 
                   //will throw error if no scriptmanager- which doesn't matter
                } 
            }
            //skip this part if not using AjaxControlToolkit or if you have it set up to get scripts from a web handler: http://blogs.msdn.com/b/delay/archive/2007/06/20/script-combining-made-better-overview-of-improvements-to-the-ajax-control-toolkit-s-toolkitscriptmanager.aspx                   
            foreach (string key in P.Request.QueryString)
            {
                //request is from AjaxControlToolkit to get scripts. Don't want to mess with the response for this
                if (key.ToLower().Contains("TSM"))
                {
                    if(P.Request.QueryString[key].ToLower().Contains("toolkitscriptmanager"))
                    return;
                }
            }
            //dont want to inject this when a page is outputting a file
            if (Response.ContentType != "text/html") { return; }

            //still going: request is for a page and its a first load or a full page postback
            Response.Write(" <script> try{ window.UserLoggedIn=" + HttpContext.Current.User.Identity.IsAuthenticated.ToString().ToLower()+ ";} catch(ex){} </script> ");
        }
        catch (Exception)
        {

        }
    }

Now client side the variable UserLoggedIn is available on every page.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.