18

I am using Adal with Azure Active Directory and I need to add extra claims via custom OwinMiddleware. When I add claims to this principal, I am able to access them in the current request. But after a page refresh, the claim is gone.

I thought Owin handled serialization of claims and put it into a cookie itself, but this doesn't seem to be the case.

I add the claims as follows:

 var claimsIdentity = (ClaimsIdentity) ClaimsPrincipal.Current.Identity;
        if (!claimsIdentity.IsAuthenticated) return;

        var identity = new ClaimsIdentity(claimsIdentity);

        var currentTenantClaim = GetTenantClaim();

        if (currentTenantClaim != null)
            claimsIdentity.RemoveClaim(currentTenantClaim);

        claimsIdentity.AddClaim(new Claim(ClaimTypes.CurrentTenantId, id));

        context.Authentication.AuthenticationResponseGrant = new AuthenticationResponseGrant
            (new ClaimsPrincipal(identity), new AuthenticationProperties {IsPersistent = true});

Any ideas on how to persist the new claims to the cookie?

BenV
  • 12,052
  • 13
  • 64
  • 92
Identity
  • 1,553
  • 1
  • 22
  • 44

2 Answers2

19

I've added the claims to the wrong Identity. They had to be added to the identity variable instead of the claimsIdentity.

Working code:

        var claimsIdentity = (ClaimsIdentity) context.Authentication.User.Identity;
        if (!claimsIdentity.IsAuthenticated) return;

        var identity = new ClaimsIdentity(claimsIdentity);

        var currentTenantClaim = GetTenantClaim(identity);

        if (currentTenantClaim != null)
            identity.RemoveClaim(currentTenantClaim);

        identity.AddClaim(new Claim(ClaimTypes.CurrentTenantId, id));

        context.Authentication.AuthenticationResponseGrant = new AuthenticationResponseGrant
            (new ClaimsPrincipal(identity), new AuthenticationProperties {IsPersistent = true});
Identity
  • 1,553
  • 1
  • 22
  • 44
4

This is what worked for me, using .NET 6:

var identity = (ClaimsIdentity)Request.HttpContext.User.Identity;
identity.AddClaim(new Claim("ClaimName", "ClaimValue"));
    

If I want to check this claim in this identity, this is what I do

var Claims = User.Claims;

Hope it might help someone

Druid
  • 6,423
  • 4
  • 41
  • 56
welly
  • 41
  • 2