首页 > 解决方案 > 如果帐户过期,则强制用户注销

问题描述

如果他的帐户过期,我正试图强制用户注销。我正在使用 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.netasp.net-mvcasp.net-core

解决方案


一个小小的误用。改变

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

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

推荐阅读