授权浏览器webAssemembly不工作

发布于 2025-02-06 17:11:16 字数 3428 浏览 1 评论 0原文

我在Blazor应用中使用身份。我将aspnetroles列为我的3个角色:“用户”“管理员”“主持人”。在成功注册时,角色和用户之间的Aspnetuserroles建立了关系。到目前为止,所有这些都起作用,但是当我试图检查角色

@attribute [Authorize(Roles = "user")]

<AuthorizeView Roles="user">...

没有看到角色时,我总是会发现视图。我应该在startup.cs或sth中以任何方式添加此角色吗? 这是我的启动

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>();
        }

。 或同样的wwith我会遇到错误,“发生了未手动错误。重新加载”。
编辑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();
        }
    }

添加在startup.cs中:

public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<RolesSeeder>();

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");
                    }

I'm using Identity in Blazor app. I sed table AspNetRoles with my 3 roles: "user" "administrator" "moderator". And on succesfully registration there is creating relation in AspNetUserRoles between role and user. 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. Should I add this roles in any way in Startup.cs or sth?
Here is my 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".

Edit 1:
Roles seeder:

 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:

public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<RolesSeeder>();

Register.cshtml added:

                    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");
                    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

顾冷 2025-02-13 17:11:16

在客户端添加中:

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);
            }
        }
    }
}

如果登录后您的播种角色。相关用户需要注销,然后再次进行索赔。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文