如何在blazor服务器端应用程序中扩展身份验证过程?

时间:2020-09-17 08:35:07

标签: c# asp.net-core blazor blazor-server-side

我在blazor服务器端应用程序中使用Cookie身份验证。

await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);

我现在想要做的是每当blazor服务器端应用验证用户授权时,在静态类中更改一个静态变量。有没有简单的方法可以做到这一点?

编辑: 这是基于Plamen Yordanov解决方案的实现。

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, configureOptions =>
                {
                    bool personalNummerConfigured = false;
                    configureOptions.Events.OnValidatePrincipal = (context) =>
                    {
                        if (!personalNummerConfigured)
                        {
                            var employeeClaim = context.Principal.Claims.Where(x => x.Type == "EmployeeId").FirstOrDefault();
                            int.TryParse(employeeClaim.Value, out int personalNummer);
                            FbController.PersonalNummer = personalNummer;
                            Console.WriteLine($"PersonalNummer: {employeeClaim.Value}");
                            personalNummerConfigured = true;
                        }
                        return Task.CompletedTask;
                    };
                });

1 个答案:

答案 0 :(得分:1)

您可以订阅某些cookie身份验证事件,并且有一个OnSignedIn event

可以在您的Startup.cs中配置此事件,如下所示:

.AddCookie("AppCookie", configureOptions => {
     configureOptions.Events.OnSignedIn = (context) => 
         {
             //handler code
             return Task.CompletedTask;
         };
 });

您可以在官方docs

中查看所有可以订阅的活动