我在改变dotnetcore身份角色时遇到一些问题.
我有以下代码
private async Task SetRoleToX(ClaimsPrincipal claimsPrincipal,string X) { var currentUser = await UserManager.GetUserAsync(claimsPrincipal); var roles = await UserManager.GetRolesAsync(currentUser); await UserManager.RemoveFromRolesAsync(currentUser,roles); await UserManager.AddToRoleAsync(currentUser,X); await SignInManager.RefreshSignInAsync(currentUser); }
我无法获得ClaimPrincipal更新.
我试过使用登录并登出.
如果手动登录,角色切换工作正常.
我一直在搜索网页,很多人说这应该工作:(
解决方法
相当烦人的是,我所要做的只是将请求发回给该请求.
我不能相信我没有想到它希望这有助于某人.
根据请求更新一些代码
// In controller public async Task SwapRole([FromBody]RoleSwapRequestDto dto) { await _service.SwapRole( User,dto.RoleName ); return await AddCookieToResponse(); } private async Task AddCookieToResponse() { // Make your token however your app does this (generic dotnet core stuff.) var response = await _tokenService.RegenToken(User); if (response.Data != null && response.Data.Authenticated && response.Data.TokenExpires.HasValue) { Response.Cookies.Append(AuthToken,response.Data.Token,new CookieOptions { HttpOnly = false,Expires = response.Data.TokenExpires.Value }); } return response; } /// inside _service public async Task SwapRole(ClaimsPrincipal claimsPrincipal,X); await SignInManager.RefreshSignInAsync(currentUser); }