asp.net-mvc 配置 ASP.NET MVC 以进行 AD 身份验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10279140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:53:04  来源:igfitidea点击:

Configure ASP.NET MVC for authentication against AD

asp.net-mvcactive-directory

提问by Ben Aston

What are the high level steps to authenticate users of an ASP.NET MVC application against Active Directory?

针对 Active Directory 对 ASP.NET MVC 应用程序的用户进行身份验证的高级步骤是什么?

I presume something like:

我假设是这样的:

  1. Modify web.config to use Windows authentication
  2. Configure web.config to use the ActiveDirectoryMembershipProvider
  3. Configure the web.config to use a custom RoleProvider that looks in AD
  1. 修改 web.config 以使用 Windows 身份验证
  2. 配置 web.config 以使用 ActiveDirectoryMembershipProvider
  3. 配置 web.config 以使用在 AD 中查找的自定义 RoleProvider

Does the above look sensible, and if so, where do I put the valid user detection logic?

以上看起来是否合理,如果是,我将有效的用户检测逻辑放在哪里?

In my case a valid user is someone on a specific AD domain.

在我的情况下,有效用户是特定 AD 域上的某个人。

回答by balexandre

Forms Authentication

表单认证

You can use the normal forms authentication to authenticate a user against an Active Directory, for that you just need you AD connection string:

您可以使用普通表单身份验证针对 Active Directory 对用户进行身份验证,为此您只需要 AD 连接字符串:

<connectionStrings>
  <add name="ADConn" connectionString="LDAP://YourConnection" />
</connectionStrings>

and add the Membership Provider to use this connection:

并添加 Membership Provider 以使用此连接:

<membership defaultProvider="ADMembership">
  <providers>
    <add name="ADMembership"
         type="System.Web.Security.ActiveDirectoryMembershipProvider,
               System.Web,
               Version=2.0.0.0, 
               Culture=neutral,
               PublicToken=b03f5f7f11d50a3a"
         connectionStringName="ADConn"
         connectionUsername="domain/user"
         connectionPassword="pwd" />
  </providers>
</membership>

you will need to use username@domainto successfully authenticate the user.

您将需要使用username@domain来成功验证用户。

Here is something to get you started

这里有一些东西可以让你开始



Windows Authentication

Windows 身份验证

If you start your project new, you can always select Intranet applicationfrom the template and all is taken care for you

如果您开始新的项目,您可以随时从模板中选择Intranet 应用程序,一切都会为您服务

enter image description here

在此处输入图片说明

If you want to do it manually, you need to change:

如果要手动进行,则需要更改:

  1. Enable Windows Authentication
  2. Disable Anonymous authentication
  1. 启用 Windows 身份验证
  2. 禁用匿名身份验证

for detailed info on doing this on IIS7/8 and IISExpress:

有关在 IIS7/8 和 IISExpress 上执行此操作的详细信息:

IIS 7 & IIS 8

  1. Open IIS Manager and navigate to your website.
  2. In Features View, double-click Authentication.
  3. On the Authentication page, select Windows authentication. If Windows authentication is not an option, you'll need to make sure Windows authentication is installed on the server.

    To enable Windows authentication on Windows: a)In Control Panel open "Programs and Features". b)Select "Turn Windows features on or off". c)Navigate to Internet Information Services > World Wide Web Services > Security and make sure the Windows authentication node is checked.

    To enable Windows authentication on Windows Server: a)In Server Manager, select Web Server (IIS) and click Add Role Services b)Navigate to Web Server > Security and make sure the Windows authentication node is checked.

  4. In the Actions pane, click Enable to use Windows authentication.

  5. On the Authentication page, select Anonymous authentication.
  6. In the Actions pane, click Disable to disable anonymous authentication.

IIS Express

  1. Right click on the project in Visual Studio and select Use IIS Express.
  2. Click on your project in the Solution Explorer to select the project.
  3. If the Properties pane is not open, open it (F4).
  4. In the Properties pane for your project: a) Set "Anonymous Authentication" to "Disabled". b) Set "Windows Authentication" to "Enabled".

IIS 7 和 IIS 8

  1. 打开 IIS 管理器并导航到您的网站。
  2. 在功能视图中,双击身份验证。
  3. 在身份验证页面上,选择 Windows 身份验证。如果 Windows 身份验证不是一个选项,您需要确保在服务器上安装了 Windows 身份验证。

    在 Windows 上启用 Windows 身份验证: a)在控制面板中打开“程序和功能”。 b)选择“打开或关闭 Windows 功能”。 c)导航到 Internet 信息服务 > 万维网服务 > 安全性并确保选中 Windows 身份验证节点。

    要在 Windows Server 上启用 Windows 身份验证: a)在服务器管理器中,选择 Web 服务器 (IIS) 并单击添加角色服务 b)导航到 Web 服务器 > 安全并确保选中 Windows 身份验证节点。

  4. 在操作窗格中,单击启用以使用 Windows 身份验证。

  5. 在身份验证页面上,选择匿名身份验证。
  6. 在操作窗格中,单击禁用以禁用匿名身份验证。

IIS Express

  1. 在 Visual Studio 中右键单击该项目并选择使用 IIS Express。
  2. 在解决方案资源管理器中单击您的项目以选择该项目。
  3. 如果“属性”窗格未打开,请将其打开 (F4)。
  4. 在项目的“属性”窗格中: a) 将“匿名身份验证”设置为“已禁用”。b) 将“Windows 身份验证”设置为“已启用”。

In your web.confighave something like

在你web.config有类似的东西

<system.web>
  <authentication mode="Windows" />

  <authorization>
    <deny users="?" />
  </authorization>
</system.web>

and that's it!

就是这样!

Now, when you want the user identity, just call

现在,当您需要用户身份时,只需调用

@User.Identity.Name

and this will show you the Domain\Usernamelike for me :

这将向您展示Domain\Username我喜欢的内容:

enter image description here

在此处输入图片说明

Here is something to get you started

这里有一些东西可以让你开始

回答by Owen Pauling

Here's a solution from the tutorial Chris Schiffhauer - Implement Active Directory Authentication in ASP.NET MVC 5:

这是教程Chris Schiffhauer - 在 ASP.NET MVC 5 中实现 Active Directory 身份验证中的解决方案:

You can secure your MVC web application on an Active Directory network by authenticating users directly against their domain credentials.

STEP 1: ACCOUNTCONTROLLER.CS

Replace your AccountController.csfile with the following:

using System.Web.Mvc;
using System.Web.Security;
using MvcApplication.Models;

public class AccountController : Controller
{
    public ActionResult Login()
    {
        return this.View();
    }

    [HttpPost]
    public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (!this.ModelState.IsValid)
        {
            return this.View(model);
        }

        if (Membership.ValidateUser(model.UserName, model.Password))
        {
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
            if (this.Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\"))
            {
                return this.Redirect(returnUrl);
            }

            return this.RedirectToAction("Index", "Home");
        }

        this.ModelState.AddModelError(string.Empty, "The user name or password provided is incorrect.");

        return this.View(model);
    }

    public ActionResult LogOff()
    {
        FormsAuthentication.SignOut();

        return this.RedirectToAction("Index", "Home");
    }
}

STEP 2: ACCOUNTVIEWMODELS.CS

Update your AccountViewModels.cs(or whatever your Account model class is named) to contain only this LoginModel class:

using System.ComponentModel.DataAnnotations;

public class LoginModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [Display(Name = "Remember me?")]
    public bool RememberMe { get; set; }
}

STEP 3: WEB.CONFIG

Finally, update your Web.configfile to include these elements.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
      <authentication mode="Forms">
          <forms name=".ADAuthCookie" loginUrl="~/Account/Login" timeout="45" slidingExpiration="false" protection="All" />
      </authentication>
      <membership defaultProvider="ADMembershipProvider">
          <providers>
              <clear />
              <add name="ADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider" connectionStringName="ADConnectionString" attributeMapUsername="sAMAccountName" />
          </providers>
      </membership>
  </system.web>
  <connectionStrings>
      <add name="ADConnectionString" connectionString="LDAP://primary.mydomain.local:389/DC=MyDomain,DC=Local" />
  </connectionStrings>
</configuration>

It may take a few steps to get your LDAP connection string:

  1. Install Remote Server Administration Tools for Windows 7. Be sure the follow the post-installation instructions to add the feature to Windows via the control panel.

  2. Open a command prompt and enter >dsquery server

    Let's say the command returns the following:

    CN=PRIMARY,CN=Servers,CN=DefaultFirstName,CN=Sites,CN=Configuration,DC=MyDomain,DC=Local
    
    • The server name is composed of the first CN value, and the two last DC values, separated by dots. So it's primary.mydomain.local.

    • The port is 389.

    • The portion of the connection string after the port and forward slash is the portion of the result beginning with the first "DC". So it's DC=MyDomain,DC=Local.

    • So the full connection string is

      LDAP://primary.mydomain.local:389/DC=MyDomain,DC=Local.
      
    • Users will login using just their username without the domain. So the correct username is Chris, not MYDOMAIN\Chris.

您可以通过直接根据用户的域凭据对用户进行身份验证来保护 Active Directory 网络上的 MVC Web 应用程序。

第 1 步:帐户控制器.CS

AccountController.cs以下内容替换您的文件:

using System.Web.Mvc;
using System.Web.Security;
using MvcApplication.Models;

public class AccountController : Controller
{
    public ActionResult Login()
    {
        return this.View();
    }

    [HttpPost]
    public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (!this.ModelState.IsValid)
        {
            return this.View(model);
        }

        if (Membership.ValidateUser(model.UserName, model.Password))
        {
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
            if (this.Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\"))
            {
                return this.Redirect(returnUrl);
            }

            return this.RedirectToAction("Index", "Home");
        }

        this.ModelState.AddModelError(string.Empty, "The user name or password provided is incorrect.");

        return this.View(model);
    }

    public ActionResult LogOff()
    {
        FormsAuthentication.SignOut();

        return this.RedirectToAction("Index", "Home");
    }
}

第 2 步:帐户视图模型.CS

更新您的AccountViewModels.cs(或您的 Account 模型类的任何名称)以仅包含此 LoginModel 类:

using System.ComponentModel.DataAnnotations;

public class LoginModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [Display(Name = "Remember me?")]
    public bool RememberMe { get; set; }
}

第 3 步:WEB.CONFIG

最后,更新您的Web.config文件以包含这些元素。

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
      <authentication mode="Forms">
          <forms name=".ADAuthCookie" loginUrl="~/Account/Login" timeout="45" slidingExpiration="false" protection="All" />
      </authentication>
      <membership defaultProvider="ADMembershipProvider">
          <providers>
              <clear />
              <add name="ADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider" connectionStringName="ADConnectionString" attributeMapUsername="sAMAccountName" />
          </providers>
      </membership>
  </system.web>
  <connectionStrings>
      <add name="ADConnectionString" connectionString="LDAP://primary.mydomain.local:389/DC=MyDomain,DC=Local" />
  </connectionStrings>
</configuration>

获取 LDAP 连接字符串可能需要几个步骤:

  1. 安装适用于 Windows 7 的远程服务器管理工​​具。确保按照安装后的说明通过控制面板将该功能添加到 Windows。

  2. 打开命令提示符并输入 >dsquery server

    假设该命令返回以下内容:

    CN=PRIMARY,CN=Servers,CN=DefaultFirstName,CN=Sites,CN=Configuration,DC=MyDomain,DC=Local
    
    • 服务器名称由第一个 CN 值和最后两个 DC 值组成,用点分隔。所以是primary.mydomain.local

    • 端口是 389。

    • 端口和正斜杠之后的连接字符串部分是结果中以第一个"DC". 所以是DC=MyDomain,DC=Local

    • 所以完整的连接字符串是

      LDAP://primary.mydomain.local:389/DC=MyDomain,DC=Local.
      
    • 用户将仅使用他们的用户名登录而不使用域。所以正确的用户名是 C​​hris,而不是 MYDOMAIN\Chris。

回答by Red_Phoenix

I found this link that checks against AD Security Groups:

我发现这个链接检查 AD 安全组:

Active Directory Authentication in ASP.NET MVC 5 with Forms Authentication and Group-Based Authorization

ASP.NET MVC 5 中的 Active Directory 身份验证与表单身份验证和基于组的授权

Only thing is this setup uses a login in page to capture the username/password credentials for AD. I changed the authentication from "FORMS" to "WINDOWS" since my app will always be accessed from within the network. Also don't forget to remove the <forms>sub-tag from the <authentication>tag if you are not going to use the FORMS authentication.

唯一的问题是此设置使用登录页面来捕获 AD 的用户名/密码凭据。我将身份验证从“FORMS”更改为“WINDOWS”,因为我的应用程序将始终可以从网络内部访问。如果您不打算使用 FORMS 身份验证,也不要忘记<forms><authentication>标签中删除子标签。