如何在 Blazor WebApp 和 Identity 中实际实现角色?

问题描述 投票:0回答:1

所以,事情是这样的:如果您创建启用了个人帐户的 Blazor WebApp (.Net8),它将为您提供一个可行的解决方案。对于开发,我使用 Sqlite。这就是它的样子(在一个其他功能齐全的应用程序中):

builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlite("Data Source=Application.db"));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddIdentityCore<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddSignInManager()
    .AddDefaultTokenProviders();

请注意AddIdentityCore中的

核心
。现在,此方法的帮助文本指出,如果您想要角色,您只需使用
AddRole<IdentityRole>
即可。对数据库的检查还发现自动创建了角色(和声明)表。

但是,当您添加

AddRoles<IdentityRole>
时,它会因为缺少
RoleManager
服务而崩溃。简单修复:只需执行
AddRoleManager<RoleManager<IdentityRole>>

这又会因为缺少

RoleStore
服务而失败。好的。所以我做了
AddRoleStore<IdentityRole>
,一切都很顺利,对吧?

不:

Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContext' while attempting to activate 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.RoleStore'

这很奇怪,因为其他所有服务都发现

DbContext
很好。那么,我该去哪里呢?

哦,使用

AddIdentity
等其他东西会让应用程序在其他位置崩溃。我有点恼火,因为所有可用的文档都没有提及
AddIdentityCore
,也没有提及添加经理和商店的必要性,在这些示例中,
AddRole
就足够了。

blazor asp.net-identity roles .net-8.0
1个回答
0
投票

最近没有理由去访问认证,所以对配置生疏了。

这是我的有效配置。区别是:

  1. 我创建了一个特定的
    IdentityDbContext
    。它指向与我的应用程序上下文相同的数据库。
  2. AddIdentity
    设置身份和角色对象。
    public static void AddAppAuthServices(this WebApplicationBuilder builder )
    {
        var dbConnectionString = builder.Configuration.GetValue<string>("DevelopmentConfiguration:DBContext");

        var services = builder.Services;

        services.AddDbContext<IdentityDbContext>(options => options.UseSqlServer(dbConnectionString));

        services.AddIdentity<IdentityUser, IdentityRole>()
            .AddEntityFrameworkStores<IdentityDbContext>();

        services.ConfigureApplicationCookie(options =>
        {
            options.LoginPath = "/Auth/Login";
            options.AccessDeniedPath = "/Auth/AccessDenied";
        });

        services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<IdentityUser>>();
    }
© www.soinside.com 2019 - 2024. All rights reserved.