how to update security stamp
when user sign out ?
is it possible to update security stamp
when user sign out ?
my code :
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));
}
error :
The instance of entity type 'User' cannot be tracked because another instance of this type with the same key is already being tracked. For new entities consider using an IIdentityGenerator to generate unique key values.
ConfigureServices :
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>();
}
Use this code:
[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");
}