Last active
March 7, 2017 07:41
-
-
Save Webbanditten/4b4391ffbbc6c395bd1721412bf8d78e to your computer and use it in GitHub Desktop.
ActiveDirectoryGroupFilter.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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