maplemale
maplemale

Reputation: 2036

HttpContext.Current.User.IsInRole("Domain\\Domain Users") takes forever

Determined this can't be a network issue. I'm having this issue in debug (VS2012 / .Net 4.5 / IIS Express 8.0)

Code:

        bool rtn2 = HttpContext.Current.User.IsInRole("MyDomain\\Domain Users");

Eventually returns true. But, can take several minutes.

        var test = HttpContext.Current;
        var test2 = HttpContext.Current.User;
        var test3 = HttpContext.Current.User.Identity;

...all extremely fast.

        var test = HttpContext.Current.User.IsInRole("MyDomain\\Domain Users");
        var test2 = HttpContext.Current.User.IsInRole("MyDomain\\Domain Users");

First call takes several minutes, the second is instant. If I change the second to look for some other group (assuming the first was cached), it is still instant.

I thought maybe i'm having network issues (I connect to the domain and debug over VPN.) However, if I create a new VS2012 web project and put that code in the startup page, it's instant. I can also search Active Directory from my machine and pull up the Domain Users group and see all people in it pretty much instantly (there are over 10 thousand users) - no problem. So, this must be project / config based issue?

Going out of my mind trying to figure this out. Some info:

Tried re-installing IIS Express I've tried rebooting I've tried in a new tester web project - works instantly

Problem seems to be machine specific. Any assistance or even just recommendations for additional trouble-shooting steps would be appreciated.

Upvotes: 3

Views: 4964

Answers (2)

Karlth
Karlth

Reputation: 3275

I had the same problem. IsInRole was taking forever to finish on a production server. The following code worked instead. Saw it somewhere, unfortunately can't remember the source.

// Is in AD Group?
private static bool IsInADGroup(String inGroup)
{
    foreach (System.Security.Principal.IdentityReference group in
        System.Web.HttpContext.Current.Request.LogonUserIdentity.Groups)
    {
        String sGroup = (group.Translate(typeof(System.Security.Principal.NTAccount)).ToString());
        if (sGroup.Equals(inGroup))
            return true;
    }
    return false;
}

Upvotes: 1

Ashigore
Ashigore

Reputation: 4678

Try using the System.DirectoryServices.AccountManagement namespace instead.

public static bool IsUserGroupMember(string userName, string groupName)
{
    using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
    using (UserPrincipal user = UserPrincipal.FindByIdentity(context, userName))
    using (PrincipalSearchResult<Principal> groups = user.GetAuthorizationGroups())
    {
        return groups.OfType<GroupPrincipal>().Any(g => g.Name.Equals(groupName, StringComparison.OrdinalIgnoreCase));
    }
}

Upvotes: 3

Related Questions