相关疑难解决方法(0)

如何在不使用FormsAuthentication.RedirectFromLoginPage时将Request.IsAuthenticated设置为true?

我正在使用表单身份验证并向服务器发送Aajx请求以进行身份​​验证.根据json结果,客户决定去哪里和做什么.这就是我没有使用FormsAuthentication.RedirectFromLoginPage来干扰ajax/json响应的原因.

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

FormsAuthentication.SetAuthCookie(username, false);
Run Code Online (Sandbox Code Playgroud)

虽然第二个参数persistent cookie是false,但cookie在浏览器会话中仍然有效.

知道如何在不使用FormsAuthentication.RedirectFromLoginPage的情况下进行Request.IsAuthenticated工作吗?

asp.net authentication ajax json asp.net-membership

26
推荐指数
2
解决办法
5万
查看次数

.net表单身份验证 - 手动设置HttpContext.Current.User在自定义AuthorizeAttribute中不起作用

我已经打了好几个小时了,我很难过.我正在向MVC 5控制器发出ajax post请求,试图自动登录特定的预定义"超级"用户.在控制器方法中,我正在尝试以编程方式设置HttpContext.Current.User并进行身份验证,因此超级用户可以跳过手动登录的过程.对此的共识似乎就在这里,我实现了:

设置HttpContext.Current.User

这似乎有效,直到我尝试使用自定义AuthorizeAttribute查看任何其他控制器方法.

控制器方法:

[HttpPost]
[AllowAnonymous]
public ActionResult Login(string username)
{
    string password = ConfigurationManager.AppSettings["Pass"];

    User user = service.Login(username, password);

    var name = FormsAuthentication.FormsCookieName;
    var cookie = Response.Cookies[name]; 
    if (cookie != null)
    {   
        var ticket = FormsAuthentication.Decrypt(cookie.Value);
        if (ticket != null && !ticket.Expired)
        {
            string[] roles = (ticket.UserData as string ?? "").Split(',');
            System.Web.HttpContext.Current.User = new GenericPrincipal(new FormsIdentity(ticket), roles);
        }
    }

    //...processing result

    return Json(result);
}
Run Code Online (Sandbox Code Playgroud)

上面的service.Login方法创建cookie:

FormsAuthentication.SetAuthCookie(cookieValue, false);
Run Code Online (Sandbox Code Playgroud)

虽然我正在设置具有Identity和IsAuthenticated的User,但下面的filterContext.HttpContext.User不是同一个用户.它本质上是空的,好像从未分配过,并且未经过身份验证.

public override void OnAuthorization(AuthorizationContext filterContext) 
{
    string[] userDetails = …
Run Code Online (Sandbox Code Playgroud)

.net asp.net-mvc forms-authentication httpcontext

12
推荐指数
1
解决办法
2651
查看次数