Lastwall Lastwall - 1 month ago 22
C# Question

ASP.Net MVC with Active Directory Authentication using Owin Middleware

I need to create an ASP.NET MVC 5 application that would use a form (like when using Individual User Accounts) for login but instead of using user info in the database, use the Windows / AD account and credentials.

In other words like using Windows Authentication but using an html form instead of the popup Windows authentication usually shows. Is this possible?

Ideally authentication would be relegated to IIS and use the same protocols and allow or deny users based on roles.

How can I do this?

What do I need to configure in the web.config?

What do I need to have in Startup.Auth.cs?

Win Win
Answer

I created a sample project at GitHub called AspNetMvcActiveDirectoryOwin. You can fork it.

There are few steps you will want to following -

First of all, you want to authenticate with Active Directory.

public class ActiveDirectoryService : IActiveDirectoryService
{
    public bool ValidateCredentials(string domain, string userName, string password)
    {
        using (var context = new PrincipalContext(ContextType.Domain, domain))
        {
            return context.ValidateCredentials(userName, password);
        }
    }

    public User GetUser(string domain, string userName)
    {
        User result = null;
        using (var context = new PrincipalContext(ContextType.Domain, domain))
        {
            var user = UserPrincipal.FindByIdentity(context, userName);
            if (user != null)
            {
                result = new User
                {
                    UserName = userName,
                    FirstName = user.GivenName,
                    LastName = user.Surname
                };
            }
        }
        return result;
    }
}

Second, you want to create claims which will be used in Owin Middleware.

public class OwinAuthenticationService : IAuthenticationService
{
    private readonly HttpContextBase _context;
    private const string AuthenticationType = "ApplicationCookie";

    public OwinAuthenticationService(HttpContextBase context)
    {
        _context = context;
    }

    public void SignIn(User user)
    {
        IList<Claim> claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, user.UserName),
            new Claim(ClaimTypes.GivenName, user.FirstName),
            new Claim(ClaimTypes.Surname, user.LastName),
        };

        ClaimsIdentity identity = new ClaimsIdentity(claims, AuthenticationType);

        IOwinContext context = _context.Request.GetOwinContext();
        IAuthenticationManager authenticationManager = context.Authentication;

        authenticationManager.SignIn(identity);
    }

    public void SignOut()
    {
        IOwinContext context = _context.Request.GetOwinContext();
        IAuthenticationManager authenticationManager = context.Authentication;

        authenticationManager.SignOut(AuthenticationType);
    }
}
Comments