简体   繁体   中英

ASP.NET MVC 5 Authentication based on IIS server's Windows domain

I need to create an ASP.NET MVC 5 Web Application project that will be accessible through Internet. It will run on an IIS server that belongs to a Windows Domain and already authenticates user through plain HTTP auth for some URLs (accepting domain user accounts).

For my project, I'd like to have a login page that will ask for username and password and authenticate against the same Windows domain. The user won't login with its local Windows domain user. I've found references to similar questions, but using Forms authentication, or ASP.NET 2.0, and I guess it's not the way I should do it using newer infrastructure.

I'm using Visual Studio 2013 Web Express and, when I create a new Project using .NET Framework 4.5 templates, it allows me to choose between No Authentication, Individual User Accounts, Organizational Accounts or Windows Authentication.

I've researched a lot before asking here but I didn't find any clue about which of the three last options will allow me to configure my app the way I want, although I think that Windows Authentication is restricted only for intranet applications.
In my research, I became aware of System.DirectoryServices.dll, but I'm not sure if this is the way I'd implement the authentication logic.

Any hints / links will be very appreciated, but sample code is always better.

Thanks!

Here's a method that uses the PrincipalContext (System.DirectoryServices.AccountManagement) to validate domain credentials.

public static bool ValidateDomainCredentials(string username, string password)
{

    if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
    {
        return false;
    }

    using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "mydomain"))
    {
           return pc.ValidateCredentials(username, password);
    }
}

Call this before signing in to make sure the user is in the active directory.

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    ...
    var user = await UserManager.FindByNameAsync(model.Username);
    if (user != null && ValidateDomainCredentials(user.user_Name, model.Password))
    {
        await SignInAsync(user, model.RememberMe);
        return RedirectToLocal(returnUrl);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM