I am quite new to Blazor and I am trying to understand authentication and authorization. What I did so far is reading the docs Authentication and Authorization in ASP.NET Core Blazor and Rolebased Authorization in Asp.NET Core. I managed to get authentication running, but I am struggeling with authorization. I would like to store every windows user who is visiting my server side app in a database and say User1 is Admin, User2 is Editor etc. and showing users diffrent areas of pages.
I was able to read out Windows users, but until now I couldn't set roles. I tried something like this with claims
:
public class CustomAuthenticationStateProvider : AuthenticationStateProvider
{
public override Task<AuthenticationState> GetAuthenticationStateAsync()
{
var identity = new ClaimsIdentity(new[]
{
new Claim( type: ClaimTypes.Name, value: @"User1")
}, "Editor");
var user = new ClaimsPrincipal(identity);
return Task.FromResult(new AuthenticationState(user));
}
}
And I attached it into ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddAuthorizationCore();
services.AddScoped<AuthenticationStateProvider, CustomAuthenticationStateProvider>();
}
From what I understand is that this function will not work with
<AuthorizeView Roles="Editor">
<p>Show User Identity: @context.User.Identity</p>
</AuthorizeView>
on razor
pages because Roles
simply are not Claims
. But how can I tell my application that User1 is in Role "Editor" and User2 is in role "Admin"? Or is there another way to ask for Users claims and show the User different areas of a page? Am I missing something?