Skip to content

Instantly share code, notes, and snippets.

@tonyjoanes
Last active November 6, 2015 13:13
Show Gist options
  • Save tonyjoanes/d97c35bf4e6b319e6f49 to your computer and use it in GitHub Desktop.
Save tonyjoanes/d97c35bf4e6b319e6f49 to your computer and use it in GitHub Desktop.
Custom authorize filter for restricting access based on group
public class AuthoriseAdAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var groupList = GetGroupList();
if (base.AuthorizeCore(httpContext))
{
if (string.IsNullOrEmpty(groupList))
return true;
var groups = groupList.Split(',').ToList();
var context = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");
var userPrincipal = UserPrincipal.FindByIdentity(
context,
IdentityType.SamAccountName,
httpContext.User.Identity.Name);
if (userPrincipal == null)
return false;
try
{
foreach (var group in groups)
if (userPrincipal.IsMemberOf(context,
IdentityType.Name,
group))
return true;
}
catch
{
return false;
}
}
return false;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
var result = new ViewResult
{
ViewName = "NotAuthorized",
MasterName = "_Layout"
};
filterContext.Result = result;
}
else
base.HandleUnauthorizedRequest(filterContext);
}
private static string GetGroupList()
{
var groupList = WebConfigurationManager.AppSettings["ADGROUPS"];
return groupList;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment