diff --git a/Source/Csla.AspNetCore/Blazor/ApplicationContextManagerInMemory.cs b/Source/Csla.AspNetCore/Blazor/ApplicationContextManagerInMemory.cs index 4ea7b14a9f..068fc1b5c8 100644 --- a/Source/Csla.AspNetCore/Blazor/ApplicationContextManagerInMemory.cs +++ b/Source/Csla.AspNetCore/Blazor/ApplicationContextManagerInMemory.cs @@ -128,10 +128,42 @@ public IPrincipal GetUser() } /// - /// Not supported in Blazor. + /// Attempts to set the current principal on the registered + /// IHostEnvironmentAuthenticationStateProvider service. /// /// Principal object. - public virtual void SetUser(IPrincipal principal) => throw new NotSupportedException(nameof(SetUser)); + public virtual void SetUser(IPrincipal principal) + { + if (!ReferenceEquals(CurrentPrincipal, principal)) + { + if (ActiveCircuitState.CircuitExists) + { + if (principal is ClaimsPrincipal claimsPrincipal) + { + SetHostPrincipal(Task.FromResult(new AuthenticationState(claimsPrincipal))); + } + else + { + throw new ArgumentException("typeof(principal) != ClaimsPrincipal"); + } + } + else if (HttpContext is not null) + { + HttpContext.User = (ClaimsPrincipal)principal; + } + else + { + throw new InvalidOperationException("HttpContext==null, !CircuitExists"); + } + CurrentPrincipal = principal; + } + } + + private void SetHostPrincipal(Task task) + { + if (AuthenticationStateProvider is IHostEnvironmentAuthenticationStateProvider hostProvider) + hostProvider.SetAuthenticationState(task); + } /// /// Gets the local context.