Reputation: 10730
Long story short, I use Identity and in my solution I created a custom account settings page which works fine and dandy. The problem is that I have the users FirstName
and LastName
in the _Layout.cshtml
. The name is set by a custom helper method I have:
public static MvcHtmlString GetUsersFirstAndLastName(this HtmlHelper helper)
{
string fullName = HttpContext.Current?.User?.Identity?.Name ?? string.Empty;
var userIdentity = (ClaimsPrincipal)Thread.CurrentPrincipal;
var nameClaim = identity?.FindFirst("fullname");
if (nameClaim != null)
{
fullName = nameClaim.Value;
}
return MvcHtmlString.Create(fullName);
}
This method works great, until a user goes to their profile and updates their name. If they change their name from George
to Bob
then when they go around on my website this method still pulls their name as George
until they log out and log back in.
So what I did to fix that was when they update their name in the account settings I added some code to remove their old fullName
claim, and add the new one, like this:
var identity = User.Identity as ClaimsIdentity;
// check for existing claim and remove it
var currentClaim = identity.FindFirst("fullName");
if (currentClaim != null)
identity.RemoveClaim(existingClaim);
// add new claim
var fullName = user.FirstName + " " + user.LastName;
identity.AddClaim(new Claim("fullName", fullName));
With this bit of code the _Layout
view now updates the name (in our previous example George
will now change to Bob
). However, the moment the click out of that view to another place on the website or the moment they refresh the page it changes right back to George
.
Still being a bit new to identity I'm a bit puzzled why this new updated claim does not work after they click around to a different page or refresh. Any help is appreciated. :)
Upvotes: 4
Views: 2857
Reputation: 10730
When adding the new claim you also needed to do this:
var authenticationManager = HttpContext.GetOwinContext().Authentication;
authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(identity), new AuthenticationProperties() { IsPersistent = true });
So the new full code block is:
public static MvcHtmlString GetUsersFirstAndLastName(this HtmlHelper helper)
{
string fullName = HttpContext.Current?.User?.Identity?.Name ?? string.Empty;
var userIdentity = (ClaimsPrincipal)Thread.CurrentPrincipal;
var nameClaim = identity?.FindFirst("fullname");
var authenticationManager = HttpContext.GetOwinContext().Authentication;
authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(identity), new AuthenticationProperties() { IsPersistent = true });
if (nameClaim != null)
{
fullName = nameClaim.Value;
}
return MvcHtmlString.Create(fullName);
}
Upvotes: 2