Active Directory role validation takes too long

I have this code for checking group membership, but it seems that it reacts too long and slows down my application, it takes almost 7-12 seconds to respond, I just need to check for a specific group membership, is there a faster way to do this?

public static bool isInRole(UserAccount userAccount, string groupName) { using (var ctx = new PrincipalContext(ContextType.Domain, userAccount.DomainName)) { using (var grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, groupName)) { bool isInRole = grp != null && grp .GetMembers(true) .Any(m => m.SamAccountName == userAccount.UserName); return isInRole; } } 
+4
source share
2 answers

I don’t have your specific AD to verify this, but it might be worth a try: instead of checking group members for specific users (there could potentially be thousands of members), why don't you check the membership of the user group to see if the user has the correct group?

Sort of:

 public static bool isInRole(UserAccount userAccount, string groupName) { using (var ctx = new PrincipalContext(ContextType.Domain, userAccount.DomainName)) using (var user = UserPrincipal.FindByIdentity(ctx, userAccount.UserName)) { bool isInRole = user != null && user.GetAuthorizationGroups() .Any(g => g.Name == groupName); return isInRole; } } 

Maybe something around will be a little faster?

0
source

I can’t give you an answer, because we don’t have enough information, but to track your problem ...

First, try querying AD using standard tools (running on a web server) - is it just as slow? If so, it is probably a mains / dc problem.

Assuming this is your slow implementation ...

Are you calling the WCF service hosted on the website to collect / download ? To test this, make several calls and compare the delays. If the first is much longer, look at the IIS settings. 0 To reduce the problem, you can increase the downtime before downloading the application, etc.

If you are sure that your code takes too much time, use Visual Studio Pofiler , which will determine which functions / calls cause a delay - if it is in your code, optimize it. If it is within the framework, then you are either using it incorrectly or you have discovered a problem with the framework (unlikely).

If you can edit your question to include answers to the above, we can help further

Edit:. In response to the question about caching in WCF, there are several ways to approach this - you can replace the storage provider for the service class to make it single - then you can just use private variables / memory for caching. This requires your class to be thread safe.

Alternatives include: database, file system, shared cache in memory ( System.Runtime.Caching )

+1
source

All Articles