[英]AuthorizeView blazor webassembly doesn't work
I'm using Identity in Blazor app.我在 Blazor 应用程序中使用身份。 I sed table AspNetRoles with my 3 roles: "user" "administrator" "moderator".
我 sed 表 AspNetRoles 与我的 3 个角色:“用户”“管理员”“版主”。 And on succesfully registration there is creating relation in AspNetUserRoles between role and user.
成功注册后,在角色和用户之间的 AspNetUserRoles 中创建关系。 All works to this moment, but when Im trying to check role with
这一刻一切正常,但是当我试图检查角色时
@attribute [Authorize(Roles = "user")]
or或者
<AuthorizeView Roles="user">...
It doesn't see roles and I always get NotAuthorized view.它看不到角色,我总是得到 NotAuthorized 视图。 Should I add this roles in any way in Startup.cs or sth?
我应该以任何方式在 Startup.cs 中添加这个角色吗? Here is my startup.cs:
这是我的 startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR();
services.AddSingleton<TableManager>();
/* services.AddSingleton<ScoreManager>();*/
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDatabaseDeveloperPageExceptionFilter();
services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddAuthorization(options =>
{
options.AddPolicy("user", policy => policy.RequireRole("user"));
});
services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>();
services.AddAuthentication()
.AddIdentityServerJwt();
services.AddControllersWithViews();
services.AddRazorPages();
services.AddTransient<RolesSeeder>();
}
Policy doesnt work too, when I use @attribute[Authorize(Policy="user")] or same wwith I'm getting error "An unhandled error has occurred. Reload".策略也不起作用,当我使用 @attribute[Authorize(Policy="user")] 或相同的 wwith 我收到错误“发生未处理的错误。重新加载”。
Edit 1: Roles seeder:编辑 1:角色播种机:
public class RolesSeeder
{
private ApplicationDbContext dbContext;
public RolesSeeder(ApplicationDbContext dbContext)
{
this.dbContext = dbContext;
}
public async void SeedRoles()
{
var roleStore = new RoleStore<IdentityRole>(dbContext);
if(!(dbContext.Roles.Any(r => r.Name == "administrator")))
{
await roleStore.CreateAsync(new IdentityRole { Name = "administrator", NormalizedName = "administrator" });
}
if (!(dbContext.Roles.Any(r => r.Name == "user")))
{
await roleStore.CreateAsync(new IdentityRole { Name = "user", NormalizedName = "user" });
}
if (!(dbContext.Roles.Any(r => r.Name == "moderator")))
{
await roleStore.CreateAsync(new IdentityRole { Name = "moderator", NormalizedName = "moderator" });
}
await dbContext.SaveChangesAsync();
}
}
Added in Startup.cs:在 Startup.cs 中添加:
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<RolesSeeder>();
Register.cshtml added: Register.cshtml 添加:
if (user.UserName.Contains("admin"))
{
await _userManager.AddToRoleAsync(user, "administrator");
}
if (user.UserName.Contains("moderator"))
{
await _userManager.AddToRoleAsync(user, "moderator");
}
else
{
await _userManager.AddToRoleAsync(user, "user");
}
In the client add:在客户端添加:
builder.Services.AddApiAuthorization().AddAccountClaimsPrincipalFactory<CustomUserFactory>();
public class CustomUserFactory : AccountClaimsPrincipalFactory<RemoteUserAccount>
{
public CustomUserFactory(IAccessTokenProviderAccessor accessor)
: base(accessor)
{
}
public override async ValueTask<ClaimsPrincipal> CreateUserAsync(
RemoteUserAccount account,
RemoteAuthenticationUserOptions options)
{
var user = await base.CreateUserAsync(account, options);
ClaimsIdentity claimsIdentity = (ClaimsIdentity)user.Identity;
if (account is not null) {
MapArrayClaimsToMultipleSeparateClaims(account, claimsIdentity);
}
return user;
}
private void MapArrayClaimsToMultipleSeparateClaims(RemoteUserAccount account, ClaimsIdentity claimsIdentity)
{
foreach (var keyValuePair in account.AdditionalProperties) {
var key = keyValuePair.Key;
var value = keyValuePair.Value;
if (value is not null &&
value is JsonElement element && element.ValueKind == JsonValueKind.Array) {
claimsIdentity.RemoveClaim(claimsIdentity.FindFirst(keyValuePair.Key));
var claims = element.EnumerateArray()
.Select(x => new Claim(keyValuePair.Key, x.ToString()));
claimsIdentity.AddClaims(claims);
}
}
}
}
If your seeding roles after login.如果您在登录后播种角色。 The relevant user needs to logout then in again to have the claims.
相关用户需要注销然后重新登录才能拥有索赔。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.