0

I have code something like the below where at a certain point I need to update a user's claims (of type System.Security.Claims). I'm trying the RemoveClaim and AddClaim inside a method but how do I get the userIdentity from the user object in order to have access to RemoveClaim & AddClaim?

using System;
using System.Collections.Generic;
using System.Security.Claims;
    
namespace Trip.Classes.Authentication
{
    public class TripUser
    {
        public int         Id           { get; set; }
        public string      Name         { get; set; }
        public string      Email        { get; set; }
        public DateTime    LastAccessed { get; set; }
        public List<Claim> Claims       { get; set; } = new List<Claim>();
    }
}
    user.Claims = new List<Claim>
    {
        new Claim("DefaultId", DefaultId.ToString()),
        new Claim("LastAccessed", LastAccessed.ToString()),
    };
    
    
    user = await SetDefaultId(user) as TripUser;
    
    
    public async Task<TripUser> SetDefaultId(TripUser user)
    {
        int myNewDefaultId = 2;
    
        user.RemoveClaim("DefaultViewId");
        user.AddClaim(new Claim("DefaultViewId", myNewDefaultId.ToString()));
    
        return await Task.FromResult(user);
    }

NOTE: I initially tried something like the following but it doesn't work:

 user.Claims.Remove(claim => claim.Type == "DefaultViewId");
Dai
  • 141,631
  • 28
  • 261
  • 374
  • Is this helpful https://stackoverflow.com/a/22572684/6527049? – Vivek Nuna Sep 30 '22 at 17:37
  • 1
    Your `User` object is meant to be immutable - the only way you're meant to "add" or "remove" `Claim` values is via `SignInAsync` by passing a _new_ `ClaimsPrincipal` object with the desired claims. – Dai Sep 30 '22 at 17:46
  • 1
    `return await Task.FromResult(user);` <-- This is wrong. Your `SetDefaultId` method is already marked `async` so just do `return user` instead. – Dai Sep 30 '22 at 17:48
  • What is your main purpose? Would you please describe more? (The approach you used is an anti-pattern based on immutability of the user) – Amir Sep 30 '22 at 19:02

0 Answers0