【问题标题】:Is it possible to have Active Directory based Authentication and fall-back to form based Authentication in ASP.NET MVC 3是否可以在 ASP.NET MVC 3 中使用基于 Active Directory 的身份验证并回退到基于表单的身份验证
【发布时间】:2011-11-17 19:51:35
【问题描述】:

我正在对网站进行重新设计。重新设计的一部分是切换到框架 (MVC3),我希望添加的是网站安全区域基于我们的活动目录服务器自动验证用户的能力。但是,我们也有需要访问某些区域的客户。我想要回退到标准登录页面,只有在无法通过 AD 进行身份验证时才会调用该页面。有没有人做过这个/你发现的问题/等等...

我们目前只是在做标准的登录程序,但我想为内部员工简化它。

编辑:我考虑过制作一个单独的 mvc3 项目,仅供内部使用,但想知道这是否可以维护。

【问题讨论】:

    标签: asp.net-mvc-3 login active-directory


    【解决方案1】:

    我想你要找的是mixed mode authentication.

    已经提出了类似的问题,like this. 并且接受的答案是它无法完成......但是,我知道它可以完成,因为我也做了一个混合模式身份验证的项目。

    我所做的是:

    在全球web.config(所以不是views\web.config中的那个)放:

    <authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" timeout="2880" />
    </authentication>
    

    所以默认情况下它会对您的帐户控制器执行。

    那么这是我的控制器:

    [HttpGet]
    public ActionResult LogOn()
    {
        var loggedinUser = User.Identity.Name;
    
        // If the logged in user is not empty, the session is not new. 
        // so the user wants to manually log in.
        if (!string.IsNullOrEmpty(loggedinUser))
        {
            new SessionHelper(this).CleanupLeftoverCookies();
            return View();
        }
    
        // Else try to get the windows login name.
        loggedinUser = Request.ServerVariables["LOGON_USER"];
    
        // I stored my active directory domain in the settings file, you can probably do this programmatically too
        var domainName = Settings.Default.LDAPDomain;
    
        loggedinUser = loggedinUser.Replace(string.Format(CultureInfo.InvariantCulture, "{0}\\", domainName), string.Empty);
    
        // If there is no windows authentication either, let them login manually.
        if (string.IsNullOrWhiteSpace(loggedinUser))
        {
            return View();
        }
    
        // Else store the windows Authentication in a cookie
        if (ActiveDirectoryAuthentication(loggedinUser, false))
        {
            return RedirectToAction("Index", "Home");
        }
        else
        {
            ModelState.AddModelError(string.Empty, string.Format(CultureInfo.InvariantCulture, "Login using your windows account {0} failed. Please log in manually", loggedinUser));
            return View();
        }
        // And go back home.
    }
    

    【讨论】:

    • 那个项目在我的工作场所,所以除了我记得的以外,我无法提供准确的细节。我可以向您展示代码示例,但不能早于星期一。但是,该链接应该可以帮助您入门。
    • 太棒了,期待!
    • 感谢您的出发点并确认可以完成。但是,您省略了 SessionHelper 类及其 CleanupLeftoverCookies 方法的定义。因此,除非它指的是在运气好之后进行的活动,否则最好将那段代码与其余部分一起使用。谢谢! ;)
    • 对不起 CptRobby,但这是两年前的帖子。我没有这些方法的代码了。此外,我希望现在有人已经提出了更好的解决方法
    猜你喜欢
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    相关资源
    最近更新 更多