You should use the ClaimsAuthenticationManager extensibility point to pull more claims - everything you add there will automatically (and probably correctly) saved to the authentication session.
ASP.NET Added Claims are Missing
-
29-06-2022 - |
Domanda
I have an asp.net application that authenticates against a third party via ADFS. Once authentication is successful, the user is redirected to a landing page where claims for the user are pulled from a database. I populate the user's claims using the following code:
IClaimsPrincipal principal = Thread.CurrentPrincipal as IClaimsPrincipal;
IClaimsIdentity claimsIdentity = (IClaimsIdentity)principal.Identity;
foreach (string claim in customClaims)
{
Claim newClaim = new Claim(ClaimTypes.Role, claim);
claimsIdentity.Claims.Add(newClaim);
}
Once I have populated the claims, I save the IClaimsPrincipal to session. Here is where things get odd. After the user is redirected from the landing page to their desired page, the claims are missing. If I query the the claims using the following code...
IClaimsPrincipal principal= Thread.CurrentPrincipal as IClaimsPrincipal;
IClaimsIdentity claimsIdentity = (IClaimsIdentity)principal.Identity;
foreach (Claim claim in claimsIdentity.Claims)
{
Response.Write(claim.ClaimType + ": " + claim.Value + "<br/>");
}
...I don't get back any of the added claims. Instead I only have the original claim given me from ADFS (the username). The odd thing is that if I pull the IClaimsPrincipal out of Session, and query it's collection of claims, I get back all of the claims I added. What is going on here?
Soluzione
Altri suggerimenti
Try updating the session cookie after adding the claims, example:
var user = HttpContext.User as ClaimsPrincipal;
var claims = new List<Claim>();
claims.Add(new Claim("MyClaimType", "MyClaimValue"));
user.AddIdentity(new ClaimsIdentity(claims));
// Update cookie
var sam = FederatedAuthentication.SessionAuthenticationModule;
if (sam != null)
{
var token = new SessionSecurityToken(user);
sam.WriteSessionTokenToCookie(token);
}
I believe if you manipulate claims outside the "WIF controlled" methods like ClaimsAuthorizationManager then you have to manually update the authentication session cookie or else you lose all the changes.