I need to store additional user properties per user when using windows authentication and based off AD groups. What is the easiest way to do this?
Here is my code to check that a user belongs to an AD Group, i'd like this to run per user that logs on:
var domain = HttpContext.Current.User.Identity.Name.Split('\\')[0];
using (var ctx = new PrincipalContext(ContextType.Domain, domain))
using (var user = UserPrincipal.FindByIdentity(ctx, HttpContext.Current.User.Identity.Name))
{
if (user != null)
{
var groups = user.GetGroups()
.Select(x => x.SamAccountName);
if (groups.Contains("Special User"))
User.IsSpecial = true;
//something like this would be ideal
Then I would like to be able to check the property throughout the app:
public ActionResult Index()
{
if(User.IsSpecial)
{
...
}
}
Basically I need to check the AD groups of the user once to set the property and then use the property subsequently to alter page behaviour.
EDIT:
In line with @Matthijs suggestion below I had a look at Claims authentication but I can't get my claims to persist between requests. Any suggestions on how to do this? I add the claim in global.asax and read the value in my controllers.
protected void Application_AuthorizeRequest()
{
var claimsPrincipal = User as ClaimsPrincipal;
var claimsIdentity = User.Identity as ClaimsIdentity;
if (!claimsPrincipal.Claims.Where(x => x.Type == "Client").Any())
{
var domain = User.Identity.Name.Split('\\')[0];
using (var ctx = new PrincipalContext(ContextType.Domain, domain))
using (var user = UserPrincipal.FindByIdentity(ctx, HttpContext.Current.User.Identity.Name))
{
if (user != null)
{
var groups = user.GetGroups()
.Select(x => x.SamAccountName);
if (groups.Contains("Special User")
{
claimsIdentity.AddClaim(new Claim("IsSpecial", "Yes"));
}
Controller:
var claimsPrincipal = User as ClaimsPrincipal;
var isSpecial = claimsPrincipal.Claims.Where(x => x.Type == "IsSpecial").First().Value;