Skip to content

Instantly share code, notes, and snippets.

@Webbanditten
Last active March 7, 2017 07:41
Show Gist options
  • Save Webbanditten/4b4391ffbbc6c395bd1721412bf8d78e to your computer and use it in GitHub Desktop.
Save Webbanditten/4b4391ffbbc6c395bd1721412bf8d78e to your computer and use it in GitHub Desktop.
ActiveDirectoryGroupFilter.cs
using System;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
public class ActiveDirectoryGroupFilter : ActionFilterAttribute
{
public string Role { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (Role != null && !IsUserInGroup(Role))
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary { { "controller", "Error" }, { "action", "NotAuthorized" } });
}
base.OnActionExecuting(filterContext);
}
public bool IsUserInGroup(string roleName)
{
try
{
var user = UserPrincipal.FindByIdentity(
new PrincipalContext(ContextType.Domain),
HttpContext.Current.User.Identity.Name);
return user != null && user.GetGroups().Any(result => roleName == result.SamAccountName);
}
catch (Exception e)
{
throw e;
}
}
public string[] GetGroupsForUser()
{
var groups = new List<string>();
try
{
var user = UserPrincipal.FindByIdentity(
new PrincipalContext(ContextType.Domain),
HttpContext.Current.User.Identity.Name);
if (user != null) groups.AddRange(user.GetGroups().Select(result => result.SamAccountName));
}
catch (Exception e)
{
throw e;
}
return groups.ToArray();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment