Search code examples
c#azure-active-directoryadal

Update claims in ClaimsPrincipal


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?


Solution

  • 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});