1
votes

I am using Cookie authentication in a blazor server side app.

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

What I am trying to do now is to change a static variable in a static class whenever the blazor server side app is validating the user authorization. Is there any easy way to do this?

EDIT: Here is the implementation based on Plamen Yordanov's solution.

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
Avoid static as much as you can. Especially for Authorization. - Henk Holterman

1 Answers

2
votes

You can subscribe to certain cookie authentication events and there is an OnSignedIn event.

This event can be configured in your Startup.cs like this:

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

You can check all the events you can subscribe to in the official docs