且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用表单身份验证和Windows身份验证的Active Directory

更新时间:2022-10-24 18:34:14

我已经做到了.基本思想是,身份验证的主要形式是表格.但是,您可以使默认登录页面使用Windows身份验证.如果Windows身份验证成功,则可以创建Forms票证并继续.如果没有,则显示登录页面.

唯一需要注意的是,由于Windows身份验证始终向浏览器发送401响应(挑战Windows凭据),因此非域用户将始终会弹出一个凭据弹出窗口,必须单击取消"./p>

我在项目中使用了MVC.我的Windows登录页面是/Login/Windows,我的手动登录页面是/Login.

以下是我的web.config的相关区域:

<system.web>
  <authentication mode="Forms">
    <forms loginUrl="~/Login/Windows" defaultUrl="~/" name=".MVCFORMSAUTH" protection="All" timeout="2880" slidingExpiration="true" />
  </authentication>
<system.web>

<location path="Login">
  <system.web>
    <authorization>
      <allow users="?" />
      <allow users="*" />
    </authorization>
  </system.web>
</location>
<location path="Login/Windows">
  <system.webServer>
    <security>
      <authentication>
        <windowsAuthentication enabled="true" />
        <anonymousAuthentication enabled="false" />
      </authentication>
    </security>
    <httpErrors errorMode="Detailed" />
  </system.webServer>
  <system.web>
    <authorization>
      <allow users="?" />
    </authorization>
  </system.web>
</location>

这是我的LoginController:

[RoutePrefix("Login")]
public class LoginController : Controller {

    [Route("")]
    public ActionResult Login() {
        //Clear previous credentials
        if (Request.IsAuthenticated) {
            FormsAuthentication.SignOut();
            Session.RemoveAll();
            Session.Clear();
            Session.Abandon();
        }
        return View();
    }

    [Route("")]
    [HttpPost]
    public ActionResult TryLogin(string username, string password) {
        //Verify username and password however you need to

        FormsAuthentication.RedirectFromLoginPage(username, true);
        return null;
    }

    [Route("Windows")]
    public ActionResult Windows() {
        var principal = Thread.CurrentPrincipal;
        if (principal == null || !principal.Identity.IsAuthenticated) {
            //Windows authentication failed
            return Redirect(Url.Action("Login", "Login") + "?" + Request.QueryString);
        }

        //User is validated, so let's set the authentication cookie
        FormsAuthentication.RedirectFromLoginPage(principal.Identity.Name, true);
        return null;
    }
}

您的登录视图将只是执行POST到/Login的普通用户名/密码形式.

这时,您拥有一个/Login页面,人们可以手动进入该页面.您还拥有一个/Login/Windows页面,这是用户自动重定向到的默认登录页面.但是,如果Windows登录失败,它将显示一个通用的401错误页面.