Configure ASP.NET MVC for authentication against AD

前端 未结 3 1319
悲&欢浪女
悲&欢浪女 2020-11-30 18:32

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

I presume something like:

  1. Modify web.config
相关标签:
3条回答
  • 2020-11-30 18:44

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

    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.cs file 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.config file 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.

    0 讨论(0)
  • 2020-11-30 18:46

    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:

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

    and add the Membership Provider to use this connection:

    <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@domain to successfully authenticate the user.

    Here is something to get you started

    • http://helios.ca/2009/05/04/aspnet-mvc-forms-authentication-with-active-directory/

    Windows Authentication

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

    enter image description here

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

    1. Enable Windows Authentication
    2. Disable Anonymous authentication

    for detailed info on doing this on IIS7/8 and 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".

    In your web.config have something like

    <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\Username like for me :

    enter image description here

    Here is something to get you started

    • http://www.asp.net/mvc/tutorials/older-versions/security/authenticating-users-with-windows-authentication-cs
    0 讨论(0)
  • 2020-11-30 18:56

    I found this link that checks against AD Security Groups:

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

    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.

    0 讨论(0)
提交回复
热议问题