0

I want to update the user's claims using HttpContext.User instance, but after updating the claims they only stay within the scope of the current request. I need to make it persist for the upcoming requests as well, please help me out with this.

Please find my code below. In the POST method I update the claim and next time when the GET method is hit, I am trying to get the updated value but I get the old value.

[Route("login")]
public class LoginController : Controller
{

    private readonly IList<User> users = new List<User>
    {
        new User { UserName = "admin", Password = "1234", Role="Administrator"},
        new User { UserName = "user", Password ="1234", Role="User"}
    };
    private IConfiguration _config;

    public LoginController(IConfiguration config)
    {
        this._config = config;
    }

    [HttpGet("Enter")]
    public IActionResult Login([FromQuery]string username, [FromQuery]string password)
    {
        User login = new User();
        login.UserName = username;
        login.Password = password;
        IActionResult response = Unauthorized();

        var user = AuthenticateUser(login);
        if(user != null)
        {
            var tokenStr = GenerateJSONWebToken(user);
            response = Ok(new { token = tokenStr });
        }
        return response;
    }

    private string GenerateJSONWebToken(User userinfo)
    {
        var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
        var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);


        var claims = new[]
        {
            new Claim("username", userinfo.UserName),
            new Claim(ClaimTypes.Role, userinfo.Role),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
        };

        var token = new JwtSecurityToken(
        issuer: _config["Jwt:Issuer"],
        audience: _config["Jwt:Issuer"],
        claims,
        expires: DateTime.Now.AddMinutes(120),
        signingCredentials: credentials
            );

        var encodettoken = new JwtSecurityTokenHandler().WriteToken(token);
        return encodettoken;

    }

    [Authorize(Roles = "Administrator")]
    [Authorize]
    [HttpPost("Post")]
    public string Post()
    {
        var identity = HttpContext.User.Identity as ClaimsIdentity;
        IList<Claim> claim = identity.Claims.ToList();
        var username = claim[0].Value;
        return "Welcome To " + username;

      // i update claim here
          var identityClaims = (ClaimsIdentity)User.Identity;
            var username = identityClaims.FindFirst("username");
            if (username != null)
                identityClaims.RemoveClaim(username);
            identityClaims.AddClaim(new Claim("username", "sample username"));
    }

    [Authorize(Roles = "Administrator, User")]
    [HttpGet("GetValue")]
    public ActionResult<IEnumerable<string>> Get()
    {
        // in the next get request i try to access the claim, but it does not have the updated value
        // instead it has the old value
        // here i have to persist the value
          var identityClaims = (ClaimsIdentity)User.Identity;
            var username = identityClaims.FindFirst("username");
        return new string[] { "Value1", "Value2", "Value3" };
    }

    private User AuthenticateUser(User login)
    {
        User entity = null;
        if (users.Where(x=>x.UserName == login.UserName && x.Password == login.Password).ToList().Count() > 0)
        {
            entity = users.Where(x => x.UserName == login.UserName && x.Password == login.Password).FirstOrDefault();
        }
        return entity;
    }
}
Dale K
  • 25,246
  • 15
  • 42
  • 71
  • Presumably the `User.Identity` is created for each request by the MVC framework itself, so any changes you make will be destroyed when your first request finishes. It will contain the claims that were in the JWT that was sent with the request, so instead of updating the claims within C# code, you should have an updated token given to the user so they can send that to your service. – Dan Rayson Apr 18 '20 at 21:57
  • Thanks for your valuable time... please have a look into this link... They have made the claims persistent..is that feasible to my problem as well? https://stackoverflow.com/questions/40660233/update-claims-in-claimsprincipal – Hari Krishnan Vasanthamani Rag Apr 19 '20 at 03:09

0 Answers0