1

Как обновить 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)); 
     } 

ошибка:

Экземпляр типа объекта «User» не могут быть отслежены, так как другой экземпляр этого типа с тем же ключом уже отслеживаются. Для новых объектов рассмотрим использование генератора IIdentityGenerator для генерации уникальных значений ключа.

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>(); 

     } 
+0

В 'GetCurrentUser': почему бы не просто вернуть' _httpContextAccessor.HttpContext.User'? Почему вы пытаетесь перезагрузить одного пользователя из базы данных? – Dmitry

+0

потому что: невозможно преобразовать из 'System.Security.Claims.ClaimsPrincipal' в 'Data.Entities.Identities.User' – StackOverflow4855

+0

Вы пытались [существующий] (https://github.com/aspnet/Identity/blob/1.0.0 -rc2/src/Microsoft.AspNetCore.Identity/UserManager.cs # L347) 'UserManager.GetUserAsync (ClaimsPrincipal principal)' вместо написания собственной реализации? – Dmitry

ответ

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"); 
} 
Смежные вопросы