如何在不使用FormsAuthentication.RedirectFromLoginPage设置Request.IsAuthenticated为真? [英] How to set Request.IsAuthenticated to true when not using FormsAuthentication.RedirectFromLoginPage?

查看:206
本文介绍了如何在不使用FormsAuthentication.RedirectFromLoginPage设置Request.IsAuthenticated为真?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用窗体身份验证和发送Aajx请求到服务器进行身份验证。基于JSON结果,客户决定去哪里,做什么。这是我没有使用FormsAuthentication.RedirectFromLoginPage不干预的AJAX / JSON响应的原因。

I am using Form Authentication and sending an Aajx request to the server for authentication. Based on the json result, the client decides where to go and what to do. That is the reason I am not using FormsAuthentication.RedirectFromLoginPage to not interfere the ajax/json response.

在这种情况下Request.IsAuthenticated返回false,即使验证与Membership.ValidateUser后用户。然后,我用设置cookie

In this case Request.IsAuthenticated returns false, even after validating the user with Membership.ValidateUser. Then I set the cookie using

FormsAuthentication.SetAuthCookie(username, false);

虽然第二个参数,永久的cookie,是假的,饼干是至今仍然在浏览器会话有效。

Although the second parameter, persistent cookie, is false, the cookie is still valid across browser sessions.

任何想法如何使Request.IsAuthenticated工作,而无需使用FormsAuthentication.RedirectFromLoginPage?

Any idea how to make Request.IsAuthenticated work without using FormsAuthentication.RedirectFromLoginPage?

推荐答案

您需要更新目前的安全主体的请求。当你调用响应。重定向(...)一个新的请求,并完成安全主体重新初始化并Request.IsAuthenticated你的情况返回true。 FormsAuthentication.RedirectFromLoginPage 内部调用响应。重定向(...)。您可以手动更新安全主体当前请求是这样的:

You need to update the current security principal for the request. When you call Response. Redirect(...) a new request is done and the security principal is reinitialized and Request.IsAuthenticated returns true in your case. FormsAuthentication.RedirectFromLoginPage internally calls Response. Redirect(...). You can manually renew the security principal for the current request like this:

public void RenewCurrentUser()
{
    System.Web.HttpCookie authCookie =
        System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
    if (authCookie != null)
    {
        FormsAuthenticationTicket authTicket = null;
        authTicket = FormsAuthentication.Decrypt(authCookie.Value);

        if (authTicket != null && !authTicket.Expired)
        {
            FormsAuthenticationTicket newAuthTicket = authTicket;

            if (FormsAuthentication.SlidingExpiration)
            {
                newAuthTicket = FormsAuthentication.RenewTicketIfOld(authTicket);
            }
            string userData = newAuthTicket.UserData;
            string[] roles = userData.Split(',');

            System.Web.HttpContext.Current.User =
                new System.Security.Principal.GenericPrincipal(new FormsIdentity(newAuthTicket), roles);
        }
    }
}

这篇关于如何在不使用FormsAuthentication.RedirectFromLoginPage设置Request.IsAuthenticated为真?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆