I'm working in C# using PrincipalContext to do a check if user is part of security group for access to the site. Site is asp.net MVC and part of an internal network with security groups set up via active directory.
Currently load times for pages are about 2.5-3 seconds on first load and then about 1.4-1.5 seconds on subsequent loads for each action. I'd like to decrease the time if possible and have set the query to check the domain of the user which cut some time out.
public override void OnAuthorization(AuthorizationContext filterContext)
{
var alias = HttpContext.Current.User.Identity.Name;
var domain = alias.Substring(0, alias.IndexOf("\\"));
alias = alias.Substring(alias.IndexOf("\\") + 1);
var accessLevel = this.Roles;
if (CheckAccess(accessLevel, alias, domain))
{
return;
}
}
private bool CheckAccess(string group, string user, string userDomain)
{
PrincipalContext ctx;
GroupPrincipal AdGroup = null;
UserPrincipal AdUser = null;
using (Forest forest = Forest.GetCurrentForest())
{
foreach(Domain domain in forest.Domains)
{
if (domain.Name.Contains("domain1"))
{
ctx = new PrincipalContext(ContextType.Domain, domain.Name, null, ContextOptions.Negotiate | ContextOptions.SecureSocketLayer, "username", "password");
if (group == "WRITE")
{
AdGroup = GroupPrincipal.FindByIdentity(ctx, "group1");
}
if (userDomain.ToLower().Contains("domain1"))
{
AdUser = UserPrincipal.FindByIdentity(ctx, user);
}
}
else if (domain.Name.Contains("domain2"))
{
if (userDomain.ToLower().Contains("domain2"))
{
ctx = new PrincipalContext(ContextType.Domain, domain.Name, null, ContextOptions.Negotiate | ContextOptions.SecureSocketLayer, "username", "password");
AdUser = UserPrincipal.FindByIdentity(ctx, user);
}
}
}
if (AdGroup != null && AdUser != null)
{
if (AdUser.IsMemberOf(AdGroup))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
}
Also first question on CodeReview, let me know if there is anything to do to improve the question that I might have missed in the FAQ.