I want to authorize a page in C# web application. This page should only be accessed by a users in a particular AD group. I have the following code and it works perfectly when I run this in debug mode (IIS Express). But when I deploy it to my local IIS it doesn't work as expected. (User groups are always returned NULL).
public static List<string> GetAdGroupsForUser(string userName, string domainName = null)
{
var result = new List<string>();
if (userName.Contains('\\') || userName.Contains('/'))
{
domainName = userName.Split(new char[] { '\\', '/' })[0];
userName = userName.Split(new char[] { '\\', '/' })[1];
}
using (PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, domainName, userName, "password"))
using (UserPrincipal user = UserPrincipal.FindByIdentity(domainContext, userName))
using (var searcher = new DirectorySearcher(new DirectoryEntry("LDAP://" + domainContext.Name)))
{
searcher.Filter = String.Format("(&(objectCategory=group)(member={0}))", user.DistinguishedName);
searcher.SearchScope = SearchScope.Subtree;
searcher.PropertiesToLoad.Add("cn");
foreach (SearchResult entry in searcher.FindAll())
if (entry.Properties.Contains("cn"))
result.Add(entry.Properties["cn"][0].ToString());
}
return result;
}
I have referred to lot of answers online. But couldn't find a proper solution. Any help or lead would be highly appreciated.
Make sure you enabled windows authentication in iis at the site level and rest of the are disabled:
Open the “Configuration Editor” for your app/site.
Navigate to the “system.web/authentication” section in Configuration Editor.
Set the authentication “mode” to “Windows” and save your changes.
Restart IIS to make sure your changes are applied and then test access – only users belonging to the permitted group should have access.
You could also try below code:
you could refer below link for more detail:
https://serverfault.com/questions/352647/restrict-access-to-iis-site-to-an-ad-group
https://forums.iis.net/t/1226581.aspx
https://forums.asp.net/t/2152453.aspx?Using+AD+groups+to+authorise+access+to+pages+using+IIS+Windows+Authentication+ASP+NET+Core+2+1