用户分配的角色仍然无法识别

Posted

技术标签:

【中文标题】用户分配的角色仍然无法识别【英文标题】:User assigned roles remain unrecognised 【发布时间】:2022-01-08 09:20:27 【问题描述】:

我正在尝试在我的项目中引入一个管理员帐户。我更新了 Startup.cs 文件以使用角色,并在 AspNetRoles 中添加了管理员和标准帐户,并使用他们的 UserID 为用户分配了管理员。相关的 [Authorize(Role = "Admin")] 也已添加到页面中,但管理员帐户仍然被拒绝访问。我似乎无法找出导致无法识别的原因,我搜索了建议实施的类似帖子

.AddRoleManager<RoleManager<IdentityRole>>()

但是,这似乎也没有帮助。将不胜感激解决此问题的任何见解。使用 Blazor wasm。提前致谢。

Startup.cs

公共类启动 公共启动(IConfiguration 配置) 配置=配置;

    public IConfiguration Configuration  get; 

    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));

        services.AddDatabaseDeveloperPageExceptionFilter();

        services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = false)
            .AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();
            
        services.AddIdentityServer()
            .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

        services.AddAuthentication()
            .AddIdentityServerJwt();

        services.AddControllersWithViews();

        services.AddRazorPages();

        services.Configure<IdentityOptions>(options =>
        options.ClaimsIdentity.UserIdClaimType = ClaimTypes.NameIdentifier);

       services.AddControllers().AddNewtonsoftJson(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize);



    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    
        if (env.IsDevelopment())
        
            app.UseDeveloperExceptionPage();
            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.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        
            endpoints.MapRazorPages();
            endpoints.MapControllers();
            endpoints.MapFallbackToFile("index.html");
        );
    

程序.cs

 public class Program

    public static void Main(string[] args)
    
        CreateHostBuilder(args).Build().Run();
    

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            
                webBuilder.UseStartup<Startup>();
            );

AspNetRoles 表

AspNetUserRoles 表

剃刀页面

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

尽管有上述实现,当登录到分配的管理员帐户时,显示的消息是

You are not authorized to access this resource.

【问题讨论】:

能否请您在服务器的启动类和客户端的程序类中显示完整的代码。您可以稍后将其删除...您使用 Blazor WebAssembly 应用程序托管吗?(客户端、服务器、共享) 当然!我已经更新最多以包含它,是的,Blazor Web Assembly 托管 【参考方案1】:

试试下面...

变化:

services.AddIdentityServer()
        .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

收件人:

// Configure identity server to put the role claim into the id token 
// and the access token and prevent the default mapping for roles in 
// the JwtSecurityTokenHandler.
            
services.AddIdentityServer()
                .AddApiAuthorization<ApplicationUser, ApplicationDbContext>(options => 
                    options.IdentityResources["openid"].UserClaims.Add("role");
                    options.ApiResources.Single().UserClaims.Add("role");
                );
            // Need to do this as it maps "role" to ClaimTypes.Role and causes issues
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("role");

【讨论】:

这成功了!非常感谢。我在这几个小时!谢谢

以上是关于用户分配的角色仍然无法识别的主要内容,如果未能解决你的问题,请参考以下文章

控制器无法识别 JWT 角色.net core 5

为啥 Discord bot 无法识别命令?

仍然收到“无法识别 URL 意外以...结尾的请求格式”

无法识别角色授权 - 带有 IdentityServer4 Cookie/Oidc 身份验证的 ASPNET CORE 5

Delete 无法识别 List 中的指针分配

Angularjs验证 - 无法识别引导日期选择器输入