Skip to content

Instantly share code, notes, and snippets.

@bcalloway
Created March 28, 2012 15:56
Show Gist options
  • Save bcalloway/2227669 to your computer and use it in GitHub Desktop.
Save bcalloway/2227669 to your computer and use it in GitHub Desktop.
AuthorizeAD filter
/// This allows you to use an authorization filter on controller actions tied to an AD Security Group, such as [AuthorizeAD(Groups = "MIS")]
public class AuthorizeADAttribute : AuthorizeAttribute {
public string Groups { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext) {
if (base.AuthorizeCore(httpContext)) {
if (String.IsNullOrEmpty(Groups))
return true;
string adPath = WebConfigurationManager.ConnectionStrings["ADPath"].ToString(); //pull the AD connection string from Web.config
DirectoryEntry directoryEntry = new DirectoryEntry();
DirectoryEntry root = new DirectoryEntry(adPath);
DirectorySearcher searcher = new DirectorySearcher();
searcher.SearchRoot = root;
searcher.SearchScope = SearchScope.Subtree;
searcher.Filter = "(SAMAccountName=" + httpContext.User.Identity.Name + ")";
searcher.CacheResults = false;
SearchResult result = searcher.FindOne();
// Get the AD groups specified in the [AuthorizeAD] attribute
// [AuthorizeAD(Groups = "MIS, Retail")]
var groups = Groups.Split(',').ToList<string>();
// Check to see if user is in the given Security Group
foreach (string group in groups) {
foreach (string member in result.Properties["memberOf"]) {
Match match = Regex.Match(member, @"CN=" + group.Trim());
if (match.Success) {
return true;
}
}
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment