VB和ASP.Net读取ActiveDirectory用户? [英] VB and ASP.Net to read ActiveDirectory users?
问题描述
我正在尝试使用VB和ASP.NET 2.0来读取ActiveDirectory组并确定当前用户是否在该组中。该名称将传递给loginStr中的函数。这应该是死的简单,但我得到了奇怪的结果,如果有人能让我知道我应该从这里寻找什么,我会很感激。
I'm attempting to use VB and ASP.NET 2.0 to read an ActiveDirectory group and determine whether the current user is in the group or not. The name is passed to the function in loginStr. It should be dead simple, but I'm getting weird results, and would appreciate it if someone could let me know what I should be looking for from here.
Public Shared Function KnownUser(ByVal loginStr As String) As Boolean
Dim isValid As Boolean
Dim strUser As String
Dim adsRoot As New DirectoryEntry("LDAP://CN=svc_githd,OU=Service Accounts,OU=User Accounts,OU=WD,OU=Americas,DC=MyCompany,DC=com")
Dim adsSearch As DirectorySearcher = New DirectorySearcher(adsRoot)
strUser = Mid(loginStr, InStr(1, loginStr, "\") + 1)
adsSearch.PropertiesToLoad.Add("sAMAccountName")
adsSearch.PropertiesToLoad.Add("memberOf")
Dim oResult As SearchResult
Dim adsGrpcn As String
isValid = False
Try
oResult = adsSearch.FindOne()
For Each adsGrpcn In oResult.GetDirectoryEntry().Properties("memberOf").Value
If adsGrpcn = "MyGroup" Then isValid = True
Next
Catch ex As Exception
Dim msg As String = ex.Message
msg = msg & "---"
End Try
Return isValid
End Function
当我使用调试器逐步执行代码时,adsGrpcn依次包含CN = SVC_HDAccounts,OU = Security,OU = Groups,OU = Americas,DC = MyCompany,DC = com中的每个字符(减去引号,课程)。我知道有一些简单的我想念。如何检查指示组内的个人用户帐户?
When I step through the code with the debugger, adsGrpcn has, in turn, each character in "CN=SVC_HDAccounts,OU=Security,OU=Groups,OU=Americas,DC=MyCompany,DC=com" (minus the quotes, of course). I know there's something simple I'm missing. How do I check individual user accounts within the group indicated?
推荐答案
尝试以下代码
Try below code
public bool VerifyUserGroup(string userName)
{
bool returnValue = false;
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOUR DOMAIN NAME");
UserPrincipal up = UserPrincipal.FindByIdentity(ctx, userName);
if (up != null)
{
string authorizeGroups = WebConfigurationManager.AppSettings["AuthorizeGroups"].ToString();
Principal principle = up.GetAuthorizationGroups().Where(x => x.Name == authorizeGroups).FirstOrDefault();
if (principle == null)
{
returnValue = false;
}
else
{
returnValue = true;
}
}
return returnValue;
}
For Each adsGrpcn In oResult.GetDirectoryEntry().Properties("memberOf").Values
您可以在此行的末尾添加一个额外的's',看看它是否有效。
You may put an extra 's' at the end of this line, and see if it does the trick.
这篇关于VB和ASP.Net读取ActiveDirectory用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!