Estoy probando el con Blazor WASN y NetCore 7.
He cogido la aplicación que se genera, en el index.razor del cliente he puesto:
@page "/"
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using System.Security.Claims
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject NavigationManager Navigation
<PageTitle>Index</PageTitle>
<h1>Hello, world!</h1>
Welcome to your new app.
<SurveyPrompt Title="How is Blazor working for you?" />
<AuthorizeView>
<Authorized>
USARIO AUTORIZADO
</Authorized>
<NotAuthorized>
USARIO NO AUTORIZADO
</NotAuthorized>
</AuthorizeView>
<AuthorizeView Roles="admin">
<Authorized>
Admin OK
</Authorized>
</AuthorizeView>
<AuthorizeView Roles="user">
<Authorized>
User OK
</Authorized>
</AuthorizeView>
<AuthorizeView Roles="yo">
<Authorized>
Yo OK
</Authorized>
</AuthorizeView>
<AuthorizeView Roles="user">
<Authorized>
User OK
</Authorized>
</AuthorizeView>
<AuthorizeView Roles="yo, user">
User y Yo Ok
</AuthorizeView>
En el program.cs del servidor:
using Bl74.Server.Data;
using Bl74.Server.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = false)
.AddRoles<IdentityRole>() //<--- PARA LOS ROLES
.AddRoleManager<RoleManager<IdentityRole>>() //<--- PARA LOS ROLES
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>();
builder.Services.AddAuthentication()
.AddIdentityServerJwt();
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
builder.Services.AddOptions();
builder.Services.AddAuthorizationCore();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseIdentityServer();
app.UseAuthorization();
app.MapRazorPages();
app.MapControllers();
app.MapFallbackToFile("index.html");
app.Run();
Ejecuto la aplicación, me registro con un usuario, me voy a la base de datos y en la tabla [AspNetRoles] me he creado 5 Roles y en la tabla [AspNetUserRoles] pongo el id del usuario y un id de [AspNetRoles]
Siempre obtengo errores del tipo:
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
Authorization failed. These requirements were not met:
RolesAuthorizationRequirement:User.IsInRole must be true for one of the following roles: (yo|user)
No coge níngun rol.
Si en alguna pagina pongo @attribute [Authorize(Roles = "user")], mismo resultado, dice que no tengo permiso.
He probado diferentes configuraciones en el program, pero siempre igual.
Me falta algo, pero no doy.
Gracias
AuthenticationStateProvider
que es la mantiene el estado de la autorización y se setea en el program de Blazor ` builder.Services.AddAuthorizationCore(); builder.Services.AddSingleton<AuthenticationStateProvider, CustomAuthStateProvider>();`, tu tienes algo así?