[英]User AD groups not returned when deployed to IIS
我想在 C# web 應用程序中授權一個頁面。 此頁面只能由特定 AD 組中的用戶訪問。 我有以下代碼,當我在調試模式(IIS Express)下運行它時它工作得很好。 但是當我將它部署到我的本地 IIS 時,它無法按預期工作。 (用戶組總是返回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;
}
我在網上參考了很多答案。 但找不到合適的解決方案。 任何幫助或領導將不勝感激。
確保在站點級別的 iis 中啟用了 windows 身份驗證,並且禁用了 rest:
打開您的應用程序/站點的“配置編輯器”。
導航到配置編輯器中的“system.web/authentication”部分。
將身份驗證“模式”設置為“Windows”並保存更改。
重新啟動 IIS 以確保應用您的更改,然后測試訪問權限 - 只有屬於允許組的用戶才能訪問。
您也可以嘗試以下代碼:
public bool AuthenticateGroup(string userName, string password, string domain, string group)
{
if (userName == "" || password == "")
{
return false;
}
try
{
DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain, userName, password);
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = "(&(objectClass=user)(|(cn=" + userName + ")(sAMAccountName=" + userName + ")))";
SearchResult result = mySearcher.FindOne();
foreach (string GroupPath in result.Properties["memberOf"])
{
if (GroupPath.Contains(group))
{
return true;
}
}
}
catch (DirectoryServicesCOMException)
{
}
return false;
}
您可以參考以下鏈接了解更多詳情:
https://serverfault.com/questions/352647/restrict-access-to-iis-site-to-an-ad-group
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.