首页 > 解决方案 > 每次更改和重新编译 blazor 代码后,如何停止 cookie 失效?

问题描述

我正在使用托管的 Blazor WebAssembly 项目模板,并且在将 cookie 设置为主要身份验证方法(也适用于 API)之后,一切都很好,直到我更改了一行代码(前端或后端),自动编译开始并重新加载网页(感谢“Start without Debugging”),但这次 auth cookie 似乎无效,我似乎不再登录。

有没有办法阻止这种行为?或者一种阻止cookie auth在不同编译之间变化的方法?

以下是我的 CookieAuthenticationEvents 实现/覆盖:

public class CookieAuth : CookieAuthenticationEvents
{
    readonly IUserService UserRepository;

    public CookieAuth(IUserService userRepository)
    {
        UserRepository = userRepository;
    }

    public override Task RedirectToLogin(RedirectContext<CookieAuthenticationOptions> context)
    {
        context.Response.StatusCode = StatusCodes.Status401Unauthorized;
        return Task.CompletedTask;
    }
    public override Task RedirectToAccessDenied(RedirectContext<CookieAuthenticationOptions> context)
    {
        context.Response.StatusCode = StatusCodes.Status401Unauthorized;
        return Task.CompletedTask;
    }
    public override async Task ValidatePrincipal(CookieValidatePrincipalContext context)
    {
        var userPrincipal = context.Principal;

        var userId = (from c in userPrincipal.Claims
                                    where c.Type == ClaimTypes.NameIdentifier
                                    select c.Value).FirstOrDefault();

        var isTeacherAndBlocked = await UserRepository.IsTeacherAndIsBlocked(userId);

        if (isTeacherAndBlocked)
        {
            context.RejectPrincipal();
            await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return;
        }

        var lastChanged = (from c in userPrincipal.Claims
                                             where c.Type == "LastChanged"
                                             select c.Value).FirstOrDefault();

        if (!DateTime.TryParse(lastChanged, out DateTime lastChangedDate))
        {
            context.RejectPrincipal();
            await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return;
        }

        if (!await UserRepository.ValidateLastChanged(lastChanged, userId))
        {
            context.RejectPrincipal();
            await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        }
    }
}

同时UserRepository.ValidateLastChanged(...)检查获取的日期字符串是否与数据库中的日期字符串匹配(这是一种判断用户是否更改密码然后从另一台设备转到旧会话的方法,在这种情况下,我希望那种会话无效)

然后是通常的Startup.cscookie 配置:

services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(options =>
            {
                options.ExpireTimeSpan = TimeSpan.FromHours(1);
                options.Cookie.SameSite = SameSiteMode.Lax;
                options.Cookie.Name = "wtf";
                options.EventsType = typeof(CookieAuth);
                options.SlidingExpiration = true;
            });

标签: c#blazorblazor-server-sideblazor-webassembly

解决方案


没关系,发现这是字符串日期之间的比较问题,只是不要这样做,用刻度线。:D


推荐阅读