Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4844

How to load user roles from Database and assign to user in blazor wasm

$
0
0

I have a Blazor WebAssembly (WASM) app hosted in ASP.NET Core that authenticates users using default ASP.NET Core Identity.

In the server project in Program.cs, I have this code:

builder.Services.AddIdentity<AppUser, IdentityRole>(options =>{    options.SignIn.RequireConfirmedAccount = true;    options.User.AllowedUserNameCharacters = "0123456789";    options.User.RequireUniqueEmail = true;}).AddRoles<IdentityRole>()  .AddRoleManager<RoleManager<IdentityRole>>()  .AddEntityFrameworkStores<DBcontext>().AddDefaultUI();builder.Services.AddIdentityServer()    .AddApiAuthorization<AppUser, DBcontext>();

And in the client project (wasm) in Program.cs I wrote this:

builder.Services.AddApiAuthorization();

I added some roles like Admin, User, ... to register user by UserManager or DbContext.

After registering

[HttpPost]public async Task<IdentityResult> AddRole(AppUser user, string RoleName){    try    {        var Role = await db.Roles.FirstOrDefaultAsync(r => r.Name == RoleName);        if (Role == null)        {            Role = new IdentityRole()                       {                            Name = RoleName,                            NormalizedName = RoleName.ToUpper()                        };            await db.Roles.AddAsync(Role);            await db.SaveChangesAsync();        }        return await um.AddToRoleAsync(user, RoleName);    }    catch (Exception ex)    {        // ....    }}

and the roles are added to the database correctly.

In the AuthorizeView tag, I wrote this:

<AuthorizeView Roles="Admin,User,Owner">

but after login of a user, this tag's children are not displayed


Viewing all articles
Browse latest Browse all 4844

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>