用戶退出時如何更新安全標記?

asp.net-core asp.net-core-mvc c# entity-framework entity-framework-core

用戶退出時如何更新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));
        }

錯誤:

無法跟踪實體類型“用戶”的實例,因為已經跟踪了具有相同密鑰的此類型的另一個實例。對於新實體,請考慮使用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>();

        }

熱門答案

使用此代碼:

[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");
}


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因