So I ended up implementing my own authorize attribute and using that:
namespace Application.Filters
{
public class AuthorizeADAttribute : AuthorizeAttribute
{
public string Groups { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (base.AuthorizeCore(httpContext))
{
/* Return true immediately if the authorization is not
locked down to any particular AD group */
if (String.IsNullOrEmpty(Groups))
return true;
// Get the AD groups
var groups = Groups.Split(',').ToList<string>();
// Verify that the user is in the given AD group (if any)
var context = new PrincipalContext(ContextType.Domain, "server");
var userPrincipal = UserPrincipal.FindByIdentity(context,
IdentityType.SamAccountName,
httpContext.User.Identity.Name);
foreach (var group in groups)
if (userPrincipal.IsMemberOf(context, IdentityType.Name, group))
return true;
}
return false;
}
}
}
And then I can simply use the following above controllers or functions
Using Application.Filters;
...
[AuthorizeAD(Groups = "groupname")]
NB: You could simply use new PrincipalContext(ContextType.Domain);
however there is a bug in .NET 4.0 that throws a (0x80005000)
error at userPrincpal.IsMemberOf(...)
. See here for details.
If you would like to know how to redirect to another page based on failed authorization, check my answer here: Adding an error message to the view model based on controller attribute in ASP.NET MVC