【问题标题】:Unable to get user Authorization Status in AuthorizeView?无法在 AuthorizeView 中获取用户授权状态?
【发布时间】:2021-06-21 07:09:45
【问题描述】:

在我的 razor 组件中,我有这个 AuthorizeView:

<AuthorizeView Roles="Administrator">
    <Authorized>
    <span>Authorized @context.User.IsInRole("Administrator")</span>
</Authorized>
<NotAuthorized>
    <span>Not Authorized @context.User.IsInRole("Administrator")</span>
</NotAuthorized>
</AuthorizeView>

我也试过把所有的角色都放在那里但没有用:

<AuthorizeView Roles="Administrator,Supervisor,Operator,Readonly">

当我使用具有管理员角色的用户登录时,用户角色似乎不是管理员。 @context.User.IsInRole("Administrator") 将始终返回 False。我正在构建的这个应用程序,一个用户只能拥有一个角色。我在这里错过了什么吗?我需要在 Program.cs 中添加任何内容吗? 这是 Program.cs 文件:

public class Program
{
    public static async Task Main(string[] args)
    {
        var builder = WebAssemblyHostBuilder.CreateDefault(args);
        builder.RootComponents.Add<App>("#bwapp");

        builder.Services.AddHttpClient("BWebApp.ServerAPI", (sp, client) =>
        {
            client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress);
            client.EnableIntercept(sp);
        })
            .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

        builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("BWebApp.ServerAPI"));

        builder.Services.AddHttpClientInterceptor();

        builder.Services.AddScoped<HttpInterceptorService>();

        builder.Services.AddTransient(typeof(IHttpRepository<>), typeof(HttpRepository<>));

        builder.Services.AddApiAuthorization();

        await builder.Build().RunAsync();
    }
}

这是 startup.cs 代码:

    public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
 Configuration.GetConnectionString("Connection")));
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseNpgsql(
                Configuration.GetConnectionString("Connection")));

        services.AddDatabaseDeveloperPageExceptionFilter();

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

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

        services.AddAuthentication()
            .AddIdentityServerJwt();

        services.AddTransient<IUnitOfWork, UnitOfWork>();

        services.AddControllersWithViews().AddNewtonsoftJson(
            op => op.SerializerSettings.ReferenceLoopHandling = 
            Newtonsoft.Json.ReferenceLoopHandling.Ignore);
        services.AddRazorPages();

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        services.AddTransient<IEmailSender, EmailSender>();
        services.Configure<AuthMessageSenderOptions>(Configuration);


    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseMigrationsEndPoint();
            app.UseWebAssemblyDebugging();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            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");
        });
    }
}

【问题讨论】:

  • 最有可能的原因是实际(角色)声明类型与预期(角色)声明类型不匹配。尝试通过检查用户的声明而不是使用扩展方法 IsInRole 来解析正确的名称。您可以通过迭代或检查视图中的 @User.Identity.Claims 属性来做到这一点,它应该包含某种带有角色声明的声明类型。
  • 你在 startup.cs 中 .AddRoles&lt;IdentityRole&gt;() 了吗?
  • @Waller 请发布您的startup. cs 代码。
  • github.com/BrianLParker/AuthApp。我将其分解为提交步骤,以帮助人们理解这些步骤。 github.com/BrianLParker/AuthApp/commits/master

标签: asp.net-core razor blazor


【解决方案1】:

这可能是因为用户角色表没有该用户与管理员角色之间的关联。或者角色表中不存在管理员角色。

【讨论】:

    猜你喜欢
    • 2012-07-07
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    • 2017-08-22
    • 1970-01-01
    • 2018-09-05
    • 2020-03-25
    • 2014-06-15
    相关资源
    最近更新 更多