是否可以在ASP.NET MVC 3中使用基于Active Directory的身份验证并回退到基于表单的身份验证

时间:2011-11-17 19:51:36

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

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

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

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

1 个答案:

答案 0 :(得分:3)

我认为你要找的是mixed mode authentication.

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

我做的是:

在全局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.
}