woggles
woggles

Reputation: 7444

How to persist custom claim when using windows authentication

I'm trying to add a claim to my MVC app when using windows authentication, but the claim doesn't persist between requests.

Any suggestions on how to do this? I am adding the claim in Application_AuthorizeRequest in global.asax and read the value in my controllers.

Global.asax:

protected void Application_AuthorizeRequest()
{
    var claimsPrincipal = User as ClaimsPrincipal;
    var claimsIdentity = User.Identity as ClaimsIdentity;
    if (!claimsPrincipal.Claims.Where(x => x.Type == "IsSpecial").Any()) \\ALWAYS TRUE!
    {
        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;

Upvotes: 0

Views: 815

Answers (1)

ste-fu
ste-fu

Reputation: 7464

This is the way it is meant to work. The user's identity is always re-created for each request, although the exact method varies between authentication methods.

Enabling windows authentication basically just means the user's name is automatically set for you as the browser sends the ticket / username / password.

Whether you use cookies, bearer tokens or windows auth, and whether you store the claims in AD, a database or in the token, you still need to add the claims at some point per request

Upvotes: 3

Related Questions