用户退出时如何更新security stamp
?
用户退出时是否可以更新security stamp
?
我的代码:
public class SignInManager : SignInManager<User>, ISignInManager
{
// other
public override async Task SignOutAsync()
{
await _userManager.UpdateSecurityStampCurrentUserAsync();
await base.SignOutAsync();
}
}
public async Task<IdentityResult> UpdateSecurityStampCurrentUserAsync()
{
return await UpdateSecurityStampAsync(GetCurrentUser());//error
}
public User GetCurrentUser()
{
if (_httpContextAccessor.HttpContext.User == null)
{
return null;
}
var userId = Guid.Parse(_httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value);
return currentUser ?? (currentUser = _users.First(d => d.Id == userId));
}
错误:
实体类型的实例&#39;用户&#39;无法跟踪,因为已经跟踪了具有相同密钥的此类型的另一个实例。对于新实体,请考虑使用IIdentityGenerator生成唯一键值。
配置服务:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<DotNetContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DotNetConnection")));
services.AddIdentity<User, Role>()
.AddEntityFrameworkStores<DotNetContext, Guid>()
.AddUserManager<UserManager>()
.AddRoleManager<RoleManager>()
.AddUserStore<UserStore>()
.AddDefaultTokenProviders();
services.AddMvc();
// Services
services.AddScoped<IUserManager, UserManager>();
services.AddScoped<IRoleManager, RoleManager>();
services.AddScoped<ISignInManager, SignInManager>();
services.AddScoped<IUserStore, UserStore>();
}
答案 0 :(得分:1)
使用此代码:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> LogOff()
{
var user = await _userManager.FindByNameAsync(User.Identity.Name);
_authenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
await _userManager.UpdateSecurityStampAsync(user.Id);
return RedirectToAction("Index", "Home");
}