Authorize(Roles = "Admin") 始终返回 ACCESS DENIED

我花了很多时间在这件事上,看起来很简单,但找不到解决方案。


创建一个项目并运行良好,登录,注册等。但授权不适用于角色。创建并设置角色:


但尝试访问时总是返回 Access Denied:


public class _ConfigurationsController : Controller

{

    [Authorize(Roles = "AdminApp")]

    public IActionResult Index()

    {

        return View();

    }

}

启动.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("MyConnection")));


    services.AddDbContext<Scaffolding_AutoGer_Context>(options =>

        options.UseSqlServer(Configuration.GetConnectionString("MyConnection")));


    services.AddDefaultIdentity<IdentityUser>()

        .AddRoles<IdentityRole>()

        .AddRoleManager<RoleManager<IdentityRole>>()

        .AddDefaultTokenProviders()

        .AddEntityFrameworkStores<ApplicationDbContext>();


    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();


    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);


}



public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)

{

    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?}");

    });

}

https://img4.mukewang.com/64eab99800015cf106130147.jpg

AspNet用户表

https://img3.mukewang.com/64eab9a50001ee3b06560123.jpg

AspNetUserRoles 表

https://img3.mukewang.com/64eab9af000128ae04890141.jpg

MVC - 脚手架项目个人账户登录.NET Core 2.1 VS 2017





慕村9548890
浏览 243回答 1
1回答

叮当猫咪

我认为您的问题与没有配置策略有关。在public void ConfigureServices(IServiceCollection services)指定这些。 services.AddAuthorization(options =>             options.AddPolicy("AdminApp",                 policy => policy.RequireClaim("Manager")));
打开App,查看更多内容
随时随地看视频慕课网APP