Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Update Claims from Another Application, Update Cookie Claims

$
0
0

The following are 2 endpoints in my controller, goal here is to pass a list of roles, and add them to the current cookie authenticated user as claims. It is worth noting this API uses both AddNegotiate and AddCookie as authentication methods.

[HttpPost("updateroles")][Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]public async Task<IActionResult> UpdateRoles([FromBody] RoleUpdateRequest request){    if (request.Roles == null)    {        return BadRequest("Roles cannot be null");    }    var currentClaimsIdentity = (ClaimsIdentity)User.Identity!;    if (currentClaimsIdentity != null)    {        try        {            var claims = request.Roles!.Select(role => new Claim(ClaimTypes.Role, role)).ToList();            currentClaimsIdentity.AddClaims(claims);            var newPrincipal = new ClaimsPrincipal(currentClaimsIdentity);            var lastAuthenticated = DateTime.UtcNow;            var authProperties = new AuthenticationProperties()            {                IsPersistent = true,                ExpiresUtc = lastAuthenticated.AddHours(_appConfiguration.CookieTimeout)            };            var claimsMessage = string.Join(", ", newPrincipal.Claims.Select(c => c.Value));            _logger.LogMessage("Updating User with Following Claims : " + claimsMessage);            // Sign in with the new principal            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, newPrincipal, authProperties);        }        catch (Exception ex)        {            _logger.LogError("Role Update Error", ex);            return StatusCode(StatusCodes.Status500InternalServerError, "An error occurred while updating roles.");        }        return Ok(new { Message = "Roles updated successfully", Roles = request.Roles });    }    return BadRequest("Unable to update roles.");}  [HttpGet("claims")]  [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]  public async Task<IActionResult> GetClaims()  {      if (User.Identity!.IsAuthenticated)      {          var userId = User.Identity!.Name;          return Ok(User.Claims.Select(c => new { c.Type, c.Value }));      }      return Unauthorized();  }

Here is my authentication configuration in my dependency injection:

 // Cookies stored key ring services.AddDataProtection()         .PersistKeysToFileSystem(new DirectoryInfo(PHYSICALPATH))         .SetApplicationName(config["CookieName"]!); services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)         .AddNegotiate() // For Windows Authentication to retrieve User Groups         .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>         {             options.Cookie.Name = config["CookieName"];             options.Cookie.Domain = config["DomainSite"];             options.Cookie.Path = "/";             options.Cookie.HttpOnly = true;             options.Cookie.SecurePolicy = CookieSecurePolicy.Always;             options.Cookie.SameSite = SameSiteMode.None;         });

If I check the claims endpoint before and after the SignIn, it remains the same and wont show new claims.

What am I doing wrong here, or what could I do differently? Goal here is another application on the domain will send a list of new roles, apply to user, and have that show in the claims for this user after new Sign In.


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>