【问题标题】:Forcing user logout if account is expired如果帐户过期,则强制用户注销
【发布时间】:2020-11-21 21:22:22
【问题描述】:

如果用户的帐户过期,我正试图强制用户退出。我正在使用 Asp.Net MVC core 3,这是我得到的解决方案之一。

我在服务“ValidateAsync”下添加了新类。

public class ValidateAsync
    {
        public static async Task ValidatingAsync(CookieValidatePrincipalContext context)
        {
            context = context ?? throw new ArgumentNullException(nameof(context));
            var claimsIdentity = context.Principal.Identity as ClaimsIdentity;
            if (claimsIdentity?.Claims == null || !claimsIdentity.Claims.Any())
            {
                await RejectPrincipal();
                return;
            }
            UserManager<IdentityUser> userManager = context.HttpContext.RequestServices.GetRequiredService<UserManager<IdentityUser>>();
            var user = await userManager.FindByNameAsync(context.Principal.FindFirstValue(ClaimTypes.NameIdentifier));
            if (user == null || user.SecurityStamp != context.Principal.FindFirst(new ClaimsIdentityOptions().SecurityStampClaimType)?.Value)
            {
                await RejectPrincipal();
                return;
            }
            async Task RejectPrincipal()
            {
                context.RejectPrincipal();
                await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            }
        }
    }

在 Startup 类中,我在 'ConfigureServices' 方法中添加:

services.ConfigureApplicationCookie(options =>
{
    
    options.Events = new CookieAuthenticationEvents
    {
        OnValidatePrincipal = ValidateAsync
    };
}).Configure<SecurityStampValidatorOptions>(options =>
{
    options.ValidationInterval = TimeSpan.Zero;
});

在这里我有一个后台进程,它将用户设置为过期,同时如果他在过期后登录,我想强制他注销。

public async Task SetExpired()
    {
        foreach(var item in _db.Institution)
        {
            if (item.SubscriptionEndDate != null)
            {
                if (item.SubscriptionEndDate == DateTime.Today) 
                {
                    item.Status = SD.StatusExpired;

                  //Here I want to check if the user is logged in, then force logout should be done.     
                  Guid securityStamp = Guid.NewGuid();
                  item.SecurityStamp = securityStamp;

                }
            }
        }
        await _db.SaveChangesAsync();
    }

我不知道我的方法是否应该按预期工作。但是启动类中的 ValidateAsync 显示以下错误:

CS0119:“ValidateAsync”是一种类型,在给定上下文中无效。

非常感谢任何帮助。

【问题讨论】:

    标签: c# asp.net .net asp.net-mvc asp.net-core


    【解决方案1】:

    一个小小的误用。改变

    options.Events = new CookieAuthenticationEvents
    {
        OnValidatePrincipal = ValidateAsync
    };
    

    options.Events = new CookieAuthenticationEvents
    {
        OnValidatePrincipal = ValidateAsync.ValidatingAsync
    };
    

    【讨论】:

      猜你喜欢
      • 2019-12-18
      • 2010-10-09
      • 2013-12-04
      • 2020-03-18
      • 1970-01-01
      • 1970-01-01
      • 2021-03-25
      • 2019-04-30
      • 2012-05-11
      相关资源
      最近更新 更多