简体   繁体   English

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

[英]Active Directory Authentication in MVC5 is not persisting

I was following Chris Schiffhauer's excellent tutorial on MVC5 authentication with Active Directory, link here . 我一直在关注Chris Schiffhauer的有关使用Active Directory进行MVC5身份验证的出色教程,请点击此处

Anyways, I've followed his instructions, and upon successful authentication, it redirects to home/index. 无论如何,我一直遵循他的指示,并且在成功通过身份验证后,它会重定向到home / index。 I know AD is working because if I use a bad password, the redirect doesn't happen and it presents an error on the login page, which is supposed to happen. 我知道AD在工作,因为如果我使用错误的密码,则不会发生重定向,并且会在登录页面上显示错误,这应该是发生的。 The issue is... Upon redirection to the home page, the auth is lost. 问题是...重定向到主页后,身份验证丢失。 I still have the option to log in which is wrong. 我仍然可以选择登录错误的地方。 Other than the inclusion of the AD auth, I'm just using the MVC site template from VS2013. 除了包含AD身份验证,我只是使用VS2013中的MVC站点模板。 I can provide plenty more code if necessary. 如果需要,我可以提供更多代码。 Ideas? 想法?

AccountController.cs (edited) 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 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...

The problem is that you're user is never assigned to the context. 问题是您的用户永远不会分配给上下文。 After you navigate to a other view, the user is lost. 导航到另一个视图后,该用户将丢失。

Take a look at this tutorial about using Forms Authentication with Active Directory. 看一下有关在Active Directory中使用表单身份验证的教程

As you can see in the tutorial this is the crucial part: 如您在本教程中所见,这是关键部分:

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

我也遇到了同样的问题,我使用了MVC5。我在global.aspx中搜索了Application_AuthenticateRequest事件处理程序,但是它不在那儿,所以我手动添加了事件处理程序并解决了问题!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM