I have a list of windows authentication groups like
- developer_group
- hr_group
- qa_group
- db_group
I want to create a custom attribute to filter which user groups are allowed to execute the API something like this. I am not sure can be done like this.
[MYcustomattribute(groups = hr_group,qa_group)]
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
First I need to get the user and that user's all groups. How do I check the user belongs to that group and allow that user to access the API?
Controller :
namespace AuthenticationSample.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
[MYcustomattribute(groups = hr_group,qa_group)]
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
Filter class:
public class MYcustomattribute : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
//You may fetch data from database here
filterContext.Controller.ViewBag.GreetMesssage = "Execute my filter";
base.OnResultExecuting(filterContext);
}
public static bool IsMemberOfGroup(string userName, string groupName)
{
if (string.IsNullOrEmpty(userName))
return false;
using (var context = new PrincipalContext(ContextType.Domain))
{
using (var user = UserPrincipal.FindByIdentity(context, userName))
{
if (user != null)
{
var groups = user.GetGroups();
foreach (var group in groups)
{
if (group.Name.Trim().ToUpper() == groupName.Trim().ToUpper())
return true;
}
}
}
}
return false;
}
}