代码之家  ›  专栏  ›  技术社区  ›  ekenman

转换后的用户在30分钟后注销

  •  0
  • ekenman  · 技术社区  · 6 年前

    我刚刚使用了一个.net Framework应用程序并将其转换为.net Core。从旧用户表导入数据时,SecurityStamp是小写的guid,例如“0e124deb-8392-4dcc-bce7-38dcc48569a2”。当用户更改密码时,他们会得到一个新的SecurfityStamp。现在它们是大写的,例如“whbxxxsqeidva7kf3t6ajj3ahwusye”。

    0 回复  |  直到 6 年前
        1
  •  1
  •   Lasanga Guruge    6 年前

    只有当用户更改密码或取消与外部登录的链接时,才会创建新的安全戳。 默认情况下,Cookie的验证时间间隔为30分钟。由于您使用的是最新的.net核心版本,因此可以在 ConfigureServices() startup.cs 以延长验证时间。

    如果时间设置为0,它将在每个请求中验证

    
    services.Configure<SecurityStampValidatorOptions>(options =>
    {
        // This is the key to control how often validation takes place
        options.ValidationInterval = TimeSpan.FromMinutes(30);
    });
    
    

    注意 userManager.UpdateSecurityStampAsync(user) . 如果您在登录后使用这个,验证很可能会失败。

    最后,如果您想用自己的方式处理这个行为,您可以编写自己的验证器并在中间件中连接

    
    services.AddAuthentication(options =>
    {
      options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
      options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
      options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    }).AddCookie(options =>
     {
        options.Events.OnValidatePrincipal = LastChangedValidator.ValidateAsync;
     });
    
    
    
    public static class LastChangedValidator
    {
        public static async Task ValidateAsync(CookieValidatePrincipalContext context)
        {
           // you can use your own logic 
    
           /* var userRepository = context.HttpContext.RequestServices.GetRequiredService<IUserRepository>();
            var userPrincipal = context.Principal;
    
            // Look for the last changed claim.
            string lastChanged;
            lastChanged = (from c in userPrincipal.Claims
                           where c.Type == "LastUpdated"
                           select c.Value).FirstOrDefault();
    
            if (string.IsNullOrEmpty(lastChanged) ||
                !userRepository.ValidateLastChanged(userPrincipal, lastChanged))
            {
                context.RejectPrincipal();
                await context.HttpContext.Authentication.SignOutAsync("MyCookieMiddlewareInstance");
            } */
        }
    }
    
    

    否则你可以处理 ValidatePrincipal()

    
    public class CustomCookieHandler: CookieAuthenticationEvents
    {
      public override Task ValidatePrincipal(CookieValidatePrincipalContext context)
      {
        return base.ValidatePrincipal(context);
      }
    }