ASP.NET MVC - 针对Active Directory对用户进行身份验证,但需要输入用户名和密码

问题描述 投票:44回答:2

我正在开发一个MVC3应用程序,需要用户对AD进行身份验证。我知道MVC3中有一个选项可以创建一个Intranet应用程序,它可以自动根据AD对用户进行身份验证,但它使用Windows身份验证并自动登录。可以在“开放”工作站上访问此应用程序,用户需要输入其域用户名和密码。任何示例或在线教程都会很棒。一个示例项目将是例外。

asp.net-mvc asp.net-mvc-2 asp.net-mvc-3 forms-authentication windows-authentication
2个回答
44
投票

您可以使用标准Internet应用程序模板和表单身份验证,并将ActiveDirectoryMembershipProvider插入web.config

<connectionStrings>
    <add name="ADConnectionString" connectionString="LDAP://YOUR_AD_CONN_STRING" />
</connectionStrings>

<system.web>
    <authentication mode="Forms">
        <forms name=".ADAuthCookie" loginUrl="~/Account/LogOn"
               timeout="15" slidingExpiration="false" protection="All" />
    </authentication>
    <membership defaultProvider="MY_ADMembershipProvider">
        <providers>
            <clear />
            <add name="MY_ADMembershipProvider" 
                 type="System.Web.Security.ActiveDirectoryMembershipProvider" 
                 connectionStringName="ADConnectionString"
                 attributeMapUsername="sAMAccountName" />
        </providers>
    </membership>
</system.web>

通过这种方式,您可以获得Internet应用程序模板登录表单,并为您验证AD。

然后它只是一些AccountController清理删除重置密码/更改密码/注册功能,只留下登录。


10
投票

如上所述,您可以使用web.config文件中定义的成员资格提供程序。

下面的代码在MVC 3模板代码的'AccountController'的实现中,并且稍作修改以与ActiveDirectory一起使用:

 [HttpPost]
    public ActionResult LogOn( LogOnModel model, string returnUrl )
    {
      if( ModelState.IsValid )
      {
        // Note: ValidateUser() performs the auth check against ActiveDirectory
        // but make sure to not include the Domain Name in the User Name
        // and make sure you don't have the option set to use Email Usernames.
        if( MembershipService.ValidateUser( model.UserName, model.Password ) )
        {
            // Replace next line with logic to create FormsAuthenticationTicket
            // to encrypt and return in an Http Auth Cookie or Session Cookie
            // depending on the 'Remember Me' option.
            //FormsService.SignIn( model.UserName, model.RememberMe );

            // Fix this to also check for other combinations/possibilities
            if (!String.IsNullOrEmpty(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }
        else
        {
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
        }
    }

如果使用.NET 3.5 - 那么请阅读this article作为替代方案:

© www.soinside.com 2019 - 2024. All rights reserved.