Custom AuthenticationStateProvider in ASP.NET Blazor
public class CustomAuthenticationStateProvider : AuthenticationStateProvider
{
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
// user is anonymous
// ClaimsIdentity claimsIdentity = new ClaimsIdentity();
// user is authenticated
ClaimsIdentity claimsIdentity = new ClaimsIdentity("test");
claimsIdentity.AddClaim(new Claim("AccessUserPages","true"));
ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
AuthenticationState authenticationState = new AuthenticationState(claimsPrincipal);
return await Task.FromResult(authenticationState);
}
}
Program.cs
builder.Services.AddScoped<AuthenticationStateProvider, CustomAuthenticationStateProvider>();
Index,razor
@page "/"
@using System.Security.Claims
@inject AuthenticationStateProvider AuthenticationStateProvider
<div>
Authentication : @authMessage
</div>
<div>
<h5>Claims</h5>
@if (claims.Any())
{
<ul>
@foreach (var claim in claims)
{
<li>@claim.Type : @claim.Value</li>
}
</ul>
}
</div>
@code
{
private string authMessage;
private IEnumerable<Claim> claims = Enumerable.Empty<Claim>();
protected override async Task OnInitializedAsync()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
authMessage = "user is authenticated";
claims = user.Claims;
}
else
{
authMessage = "user is not authenticated";
}
}
}


