开发者

How to check ASP.NET Forms Authentication Status Using Only JavaScript?

开发者 https://www.devze.com 2023-01-08 13:17 出处:网络
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. =)

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 "开发者_如何学PythonSomeFunctionWhichGetsFacebookCookies" - 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?


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;
}


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消