【问题标题】:Asp.net User is in Role but [Authorize(Roles = "Admin")] returns Authorization failedAsp.net 用户处于角色中,但 [Authorize(Roles = "Admin")] 返回授权失败
【发布时间】:2019-12-30 00:31:28
【问题描述】:

所以...我现在尝试了大约 2 个小时,但无法让它工作。

问题是,如果我尝试像这样使用基于角色的授权

[Authorize]
public ActionResult createBill() {
    return View();
}

完全没问题 但是当我尝试像这样使用它时

[Authorize(Roles = "Admin")]
public ActionResult createBill() {
    return View();
}

我只得到授权失败。在控制台中

我已经做到了

await RoleManager.CreateAsync(new IdentityRole("Admin"));
await UserManager.AddToRoleAsync(user, "Admin");
Console.WriteLine(User.IsInRole("Admin")); <- Return true

是的,我尝试重新登录 这是我的配置服务

public void ConfigureServices(IServiceCollection services) {
    services.AddLiveReload();
    services.AddDbContext<WebinterfaceDbContext>();
    services.AddIdentity<WebinterfaceUser, IdentityRole>().AddEntityFrameworkStores<WebinterfaceDbContext>();
    services.AddRazorPages().AddRazorRuntimeCompilation();
    services.AddMvc(options => { options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build())); }).AddRazorRuntimeCompilation();
    services.AddAuthorization(options => { options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Admin")); });
    services.AddControllersWithViews();
    services.Configure<KestrelServerOptions>(options => { options.AllowSynchronousIO = true; });
}

这是配置

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
    if (env.IsDevelopment()) {
        app.UseDeveloperExceptionPage();
    } else {
        app.UseExceptionHandler("/Home/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.UseLiveReload();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthorization();
    app.UseAuthentication();
    app.UseEndpoints(endpoints => {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
        endpoints.MapRazorPages();
    });
}

我使用了 AspNet MVC 的标准模板
我正在使用这些包

<PackageReference Include="EntityFramework" Version="6.3.0-preview8-19405-04" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="3.0.0-preview8.19405.7" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.0.0-preview8.19405.7" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0-preview8.19405.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.0.0-preview8.19405.11" />
<PackageReference Include="Westwind.AspnetCore.LiveReload" Version="0.1.5.2" />

还有netcoreapp3.0
我的 DbContext

public class WebinterfaceDbContext : IdentityDbContext<WebinterfaceUser> {
    public DbSet<Bill> Bills { get; set; }
    protected override void OnModelCreating(ModelBuilder builder) {
        builder.Entity<WebinterfaceUser>().Property(e => e.Servers).HasConversion(e => JsonConvert.SerializeObject(e), e => JsonConvert.DeserializeObject<Collection<Guid>>(e));
        builder.Entity<WebinterfaceUser>().Property(e => e.ApiKeys).HasConversion(e => JsonConvert.SerializeObject(e), e => JsonConvert.DeserializeObject<Collection<Guid>>(e));

        builder.Entity<Bill>().Property(e => e.Components).HasConversion(e => JsonConvert.SerializeObject(e), e => JsonConvert.DeserializeObject<Collection<BillComponent>>(e));


        base.OnModelCreating(builder);
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
        optionsBuilder.UseSqlServer("User ID=sa;Password=123456;Server=localhost;Database=Webinteface;");
    }
}

同样糟糕的是,我的 Web 界面用户中的“账单”列表从来没有被实体框架填充......我不再知道该怎么做,遇到所有这些问题是如此令人沮丧。
顺便说一句,这是我的 WebinterfaceUser

public class WebinterfaceUser : IdentityUser {
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string? Company { get; set; }

    public string Street { get; set; }

    public int StreetNumber { get; set; }

    public int Zip { get; set; }

    public string City { get; set; }

    public string Country { get; set; }

    public Collection<Guid> Servers { get; set; } = new Collection<Guid>();

    public Collection<Guid> ApiKeys { get; set; } = new Collection<Guid>() {Guid.NewGuid()};

    public Guid SupportApiKey { get; set; } = Guid.NewGuid();

    public Collection<Bill> Bills { get; set; } = new Collection<Bill>();

    public List<Bill> getBills() {
        return new WebinterfaceDbContext().Bills.Where(b => b.Recipient == this).ToList();
    }

    public List<Server> getOwnedServers() {
        ServerContext context = new ServerContext();
        return context.Servers.Where(s => Servers.Contains(s.Guid)).ToList();
    }

    public Server getServerByGuid(Guid guid) {
        return getOwnedServers().Find(s => s.Guid == guid);
    }
}

【问题讨论】:

    标签: asp.net-mvc asp.net-identity roles role-base-authorization .net-core-3.0


    【解决方案1】:

    我刚刚遇到了这个确切的问题。这是因为 dotnet core 3.0 中的授权行为发生了一些变化。

    根据Microsoft's migration docs,您必须将 app.UseAuthorization() 放在 app.UseAuthentication() 之后。一旦你这样做了,授权角色应该可以正常工作。

    【讨论】:

    • 感谢您的回复。当我有足够的时间在新创建的项目中对此进行测试时,我将对其进行测试。我已经通过使用另一个路由而不是默认的 mvc 路由来解决这个问题。我不知道它是如何正确调用的,但无论如何它只是一种解决方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-20
    • 2013-09-28
    • 2021-01-11
    • 2016-09-25
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    相关资源
    最近更新 更多