如何仅使用 JavaScript 检查 ASP.NET 表单身份验证状态?

发布于 2024-09-10 17:10:45 字数 830 浏览 0 评论 0原文

我需要这样做的原因是因为 Facebook Connect - 这是另一个故事,所以我会为您省去这个戏剧性的内容。 =)

无论如何,我有这个在 window.onload 上运行的函数:

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

所以,我需要帮助来获取标志“loggedInUsingFormsAuth”。

我不关心 cookie 中的内容,只需要知道当前用户是否经过身份验证。

我为什么要这样做?

好吧,在窗口加载时,如果用户登录到 Facebook,但没有登录到我的网站(根据表单身份验证 cookie),我想重新加载页面 - 这允许我的 ASP.NET 网站读取 HttpContext 中的 Facebook cookie 并让用户登录。我需要在 JavaScript 中执行此操作,因为在调用“SomeFunctionWhichGetsFacebookCookies”之前我没有 Facebook cookie - 这只能在 JavaScript 中完成。

那么,我如何判断当前用户是否通过 JavaScript 进行了身份验证?我是否必须手动遍历 cookie,找到我想要的并检查它?这是安全的做法吗?

或者我应该使用 RegisterClientScript 从服务器将标志写入客户端?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

递刀给你 2024-09-17 17:10:45

您可以将以下内容添加到您的 web.config 文件中。

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

然后你就可以通过 javascript 知道你是否通过了身份验证
像这样。

function isAuth() {
    var result = Sys.Services.AuthenticationService.get_isLoggedIn();
    return result;
}

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;
}
九歌凝 2024-09-17 17:10:45

比您在评论中描述的更好的方法是创建一个简单的 Web 服务,您可以调用该服务来检索该值。

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.

清音悠歌 2024-09-17 17:10:45

由于我在每次页面加载时通过服务器注册 JavaScript,因此我决定将 HttpContext.Current.Request.IsAuthenticated 属性设置到 JavaScript 本身中。

换句话说,我在 C# 本身中定义了一些 JavaScript:

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

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

然后在我的主母版页的 HTML 上:

<%= SomeClassWhichHasAcccessToHttpContext.GetMyScript() =>

通常我不会选择这样的解决方案,我通常会调用异步 Web 服务(正如 Ben 的回答所提到的)。但事实上,该属性和 JavaScript 是在页面请求的基础上进行评估的,因此对于每个给定的 HTTP 请求,该属性的评估永远不会过时。

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.

稀香 2024-09-17 17:10:45

我有一个只需要在一个地方编写代码的解决方案:

将下面的代码添加到 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)
        {

        }
    }

现在,客户端变量 UserLoggedIn 在每个页面上都可用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文