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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
In the official document (you are reading), the role based authorization is achieved via the Asp.net Core Identity. You can find it from Add Role services to Identity.
So, you could refer to the following articles to configure your application to use Asp.net Core Identity.
Introduction to Identity on ASP.NET Core
Scaffold Identity in ASP.NET Core projects.
Besides, from your description, you are using a database to store the user account, it seems that you are using Individual User Accounts. You could refer to the following sample to achieve role based authorization in asp.net core Blazor application.
- Create an asp.net core Blazor Server App and Choose “Individual User Accounts” type and keep default “Store user accounts in-app” to store SQL tables locally for identity framework.
-
Generate the database and Indentity Schema:
Using the following command in the Package Manager Console tools. More detail information, check EF Core Migrations.
add-migration InitialCreate update-database
After that, using SQL Server Management Studio(SSMS) to check tables in the database:Open the Startup.cs file, modify the “ConfigureServices” method with below change (add
.AddRoles<IdentityRole>();
). So that we can control the authorization with identity roles in the application.
public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection"))); services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddRoles<IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>(); services.AddRazorPages(); services.AddServerSideBlazor(); services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<IdentityUser>>(); services.AddDatabaseDeveloperPageExceptionFilter(); services.AddSingleton<WeatherForecastService>(); }
Running the application, and register two users:[email protected]
and[email protected]
.Then, you could find the users from the
dbo.AspNetUsers
table (via SSMS):Open the SSMS, right click the
dbo.AspNetRoles
table and click “View Data”, and add two roles (Id is a Guid):Open the SSMS, right click the
dbo.AspNetUserRoles
table and click “View Data”, copy the user id and role id to this table and add roles to the user.If you don’t want to use this method to add roles to specific user, you could use UserManager.AddToRoleAsync() method to add the specified user to the named role. You could refer this article.
-
Create the Admin page and Normal page in the Pages folder.
AdminPage.razor:
@page "/adminpage" @attribute [Authorize(Roles = "admin")] <h3>AdminPage</h3> @code { }
NormalPage.Razor
@page "/adminpage" @attribute [Authorize(Roles = "admin")] <h3>AdminPage</h3> @code { }
Modify the shared component “NavMenu” with below changes.
<AuthorizeView Roles="admin"> <li class="nav-item px-3"> <NavLink class="nav-link" href="adminpage"> <span class="oi oi-list-rich" aria-hidden="true"></span> Admin Page </NavLink> </li> </AuthorizeView> <AuthorizeView Roles="normal"> <li class="nav-item px-3"> <NavLink class="nav-link" href="normalpage"> <span class="oi oi-list-rich" aria-hidden="true"></span> Normal Page </NavLink> </li> </AuthorizeView>
Running the application, the result like this:
Reference:
Role Based Authorization In Blazor
how to use usermanager on a blazor page?
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0