Blazor Server: CascadingAuthenticationState unequal GetAuthenticationStateAsync()
Can anybody help me solve a
problem of CascadingAuthenticationState and GetAuthenticationStateAsync():
by executing the following in a Blazor Server 5.0 Application, i get the following results:
@inject CustomAuthStateProvider AuthenticationStateProvider
[CascadingParameter]
private Task<AuthenticationState> authenticationStateTask { get; set; }
AuthenticationState authenticationState = await authenticationStateTask;
bool IsAuthenticated = authenticationState.User.Identity.IsAuthenticated; // ---> False
HttpContextAccessor httpContext = new();
IsAuthenticated = httpContext.HttpContext.User.Identity.IsAuthenticated; // ---> True
authenticationState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
IsAuthenticated = authenticationState.User.Identity.IsAuthenticated; // ---> True
Why the authenticationStateTask of the CascadingAuthenticationState in 1) result is false ?
Although AuthenticationStateProvider.GetAuthenticationStateAsync() is true ??
I've implemented a CustomAuthStateProvider:
public class CustomAuthStateProvider : ServerAuthenticationStateProvider
{
public override Task<AuthenticationState> GetAuthenticationStateAsync()
{
var identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, "exampleuser"),
new Claim(ClaimTypes.Surname, "Mouse"),
new Claim(ClaimTypes.GivenName, "Micky"),
new Claim(ClaimTypes.Role, "testRole"),
}, "user authentication type");
var user = new ClaimsPrincipal(identity);
return Task.FromResult(new AuthenticationState(user));
}
public void NotifyAuthenticationStateChanged()
{
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
}
}
Startup.cs:
//services.AddAuthorization();
services.AddAuthorizationCore();
services.AddScoped<CustomAuthStateProvider>();
services.AddScoped<AuthenticationStateProvider>(provider => provider.GetRequiredService<CustomAuthStateProvider>())
services.AddScoped<IHostEnvironmentAuthenticationStateProvider>(sp => sp.GetRequiredService<CustomAuthStateProvider>());
After the successful Login:
HostAuthentication.SetAuthenticationState(Task.FromResult(new AuthenticationState(principal)));
App.razor:
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true ">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
Using the AuthenticationStateProvider instead of the CustomAuthStateProvider works fine !
Thanks for your help !!! Kind regards