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?
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.
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.
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});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With