Search code examples
c#asp.net-mvcwindows-authentication

Unable to Authenticate Users From Domain\Users Group


I'm trying to authenticate all users from a domain for my MVC application. At the moment I am testing with the user PC_NAME/Administrator.

I have tried authorising the user group from PC_NAME in my controller class as suggested in this answer.

[Authorize(Roles = "PC_NAME\\Domain Users")]

This doesn't work, I'm just prompted to login by the browser.

I have also tried this in web.config instead

<authorization>
      <allow roles="PC_NAME\Domain Users"/>
      <deny users="*"/>
</authorization>

This is also unsuccessful


For the record I tried authenticating just the Users role without specifying a domain, and I was able to access my site

[Authorize(Roles = "Users")]

It also works when I just specify a user name

[Authorize(User = "PC_NAME\\Administrator")]

How can I authenticate all users from a single domain (in this case VSD-PROMETHEUS)?


Solution

  • I got this working by creating a custom authorise attribute.

    using System;
    using System.Web;
    using System.Web.Mvc;
    
    /// <summary>
    /// Authorises User based on what domain they are on.
    /// </summary>
    public class AuthorizeDomainAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// List of domains to authorise
        /// </summary>
        public string[] Domains { get; set; }
    
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }
    
            // Get the domain part of the username
            string userDomain = httpContext.User.Identity.Name.Substring(0, httpContext.User.Identity.Name.LastIndexOf('\\'));
    
            // Check if the user is on any of the domains specified
            foreach(string domain in this.Domains)
            {
                if (userDomain == domain)
                {
                    return true;
                }
            }
    
            // Otherwise don't authenticate them
            return false;
        }
    }
    

    And then using this attribute on my controller.

    [AuthorizeDomain(Domains = new[] { "PC_NAME")]