Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 203
Identity Avatar asked Nov 17 '16 16:11

Identity


People also ask

How do I apply a claim in .NET core?

Claim based authorization checks are declarative - the developer embeds them within their code, against a controller or an action within a controller, specifying claims which the current user must possess, and optionally the value the claim must hold to access the requested resource.

What are claims in asp net identity?

Claims can be created from any user or identity data which can be issued using a trusted identity provider or ASP.NET Core identity. A claim is a name value pair that represents what the subject is, not what the subject can do.


1 Answers

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});
like image 167
Identity Avatar answered Oct 02 '22 08:10

Identity