MVC5 中的 Active Directory 身份验证不持久

Active Directory Authentication in MVC5 is not persisting

我一直在关注 Chris Schiffhauer 关于使用 Active Directory 进行 MVC5 身份验证的优秀教程,link here

无论如何,我已经按照他的指示进行了,在成功验证后,它会重定向到 home/index。我知道 AD 正在运行,因为如果我使用错误的密码,则不会发生重定向,并且它会在登录页面上显示错误,这应该会发生。问题是...重定向到主页后,身份验证丢失了。我仍然可以选择登录是错误的。除了包含 AD 身份验证之外,我只是使用 VS2013 中的 MVC 站点模板。如有必要,我可以提供更多代码。想法?

AccountController.cs(已编辑)

 if (Membership.ValidateUser(model.UserName, model.Password))
        {


            log.Info("User " + model.UserName + " is authenticated.");
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);





            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(FormsAuthentication.GetAuthCookie(model.UserName, model.RememberMe).Value); //ticket creation/decryption is successful

            GenericIdentity id = new GenericIdentity(ticket.Name, "LdapAuthentication"); // id is successful

            log.Info("ticket :" + ticket.Name);

            // This principal will flow throughout the request.
            GenericPrincipal principal = new GenericPrincipal(id, null); //making the principal works

            // Attach the new principal object to the current HttpContext object


            log.Info("principal :" + principal.Identity.Name);
            System.Web.HttpContext.Current.User = principal; // this doesn't seem to work.


            if (this.Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\"))
            {
                return this.Redirect(returnUrl);
            }

            return this.RedirectToAction("Index", "Home");
        }

Login.cshtml

...snipped for brevity...
 @using (Html.BeginForm("Login", "Account", new {ReturnUrl = ViewBag.ReturnUrl}, FormMethod.Post, new {@class = "form-horizontal", role = "form"}))
                {
                    @Html.AntiForgeryToken()
                    <h4>Use a local account to log in.</h4>
                    <hr/>
                    @Html.ValidationSummary(true, "", new {@class = "text-danger"})
                    <div class="form-group">
                        @Html.LabelFor(m => m.UserName, new {@class = "col-md-3 control-label"})
                        <div class="col-md-9">
                            @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
                            @Html.ValidationMessageFor(m => m.UserName, "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(m => m.Password, new {@class = "col-md-3 control-label"})
                        <div class="col-md-9">
                            @Html.PasswordFor(m => m.Password, new {@class = "form-control"})
                            @Html.ValidationMessageFor(m => m.Password, "", new {@class = "text-danger"})
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-md-offset-3 col-md-9">
                            <div class="checkbox">
                                @Html.CheckBoxFor(m => m.RememberMe)
                                @Html.LabelFor(m => m.RememberMe)
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-md-offset-2 col-md-10">
                            <input type="submit" value="Log in" class="btn btn-primary"/>
                        </div>
                    </div>


                }
 ...snipped for brevity...

问题是您的用户从未分配给上下文。导航到其他视图后,用户丢失了。

看看这个tutorial关于在 Active Directory 中使用表单身份验证。

正如您在教程中看到的,这是关键部分:

// Extract the forms authentication cookie
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
if(null == authCookie)
{
// There is no authentication cookie.
return;
}

FormsAuthenticationTicket authTicket = null;
try
{
      authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch (Exception ex)
{
      // Log exception details (omitted for simplicity)
      return;
}
if (null == authTicket)
{
      // Cookie failed to decrypt.
      return;
}

// Create an Identity object
GenericIdentity id = new GenericIdentity(authTicket.Name,"LdapAuthentication");

// This principal will flow throughout the request.
GenericPrincipal principal = new GenericPrincipal(id, null);

// Attach the new principal object to the current HttpContext object
Context.User = principal;

我也遇到了同样的问题,我使用的是 MVC 5。我在 global.aspx[ 中搜索了 Application_AuthenticateRequest 事件处理程序 但它不存在,然后我手动添加了事件处理程序并解决了问题!