web-dev-qa-db-ja.com

ASP.NET Core 2.1 ID:役割ベースの承認->アクセスが拒否されました

.NETの新しいIDフレームワークでASP.NETCore2.1を使用しています。通常のAuthorization属性は、ロール固有のロールが要求されていない限り機能します。

ロールを使用するには、拡張/カスタマイズされたポリシーが必要ですか?以下は私のコードの最小化されたサンプルです:

Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
        services.AddDefaultIdentity<IdentityUser>()
            .AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();

        // Does not change anything
        // services.AddAuthorization();
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }


    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseAuthentication();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

HomeController.cs

    public async Task<IActionResult> Index()
    {
        if (!await _roleManager.RoleExistsAsync("Admin"))
        {
            await _roleManager.CreateAsync(new IdentityRole("Admin"));
        }

        var user = await _userManager.FindByEmailAsync("[email protected]");
        if (!await _userManager.IsInRoleAsync(user, "Admin"))
        {
            await _userManager.AddToRoleAsync(user, "Admin");
            await _userManager.UpdateAsync(user);
        }


        return View();
    }

    [Authorize]
    public IActionResult About()
    {
        ViewData["Message"] = "Your application description page.";

        return View();
    }

    [Authorize(Roles = "Admin")]
    public IActionResult Contact()
    {
        ViewData["Message"] = "Your contact page.";

        return View();
    }
6
dannyyy

うーん。動作しているAsp.Net2.1プロジェクトに次のコードがあります。

services.AddDefaultIdentity<IdentityUser>()
         .AddRoles<IdentityRole>()
         //.AddDefaultUI(UIFramework.Bootstrap4)
         .AddDefaultTokenProviders()
         .AddEntityFrameworkStores<ApplicationDbContext>();
1
Owen