asp.net-core - ASP.NET Core 2.1 标识 : Role-based authorization -> Access Denied

标签 asp.net-core authorization asp.net-identity

我正在使用 ASP.NET Core 2.1 和来自 .NET 的新 Identity 框架。正规Authorization只要没有请求特定于角色的角色,属性就可以工作。

我是否需要一些扩展/自定义策略来使用角色?以下是我的代码的最小化示例:

启动文件

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

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

        var user = await _userManager.FindByEmailAsync("danny.meier@tpcag.ch");
        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();
    }

最佳答案

这是 2.1 版本中的已知问题并已在 2.2 preview-1 中修复.

原因是 AddDefaultIdentity<TUser>() 的新方法,这是在 ASP.NET Core 2.1 中介绍的, 不会做 Roles默认启用。

四处走走,而不是使用新的 AddDefaultIdentity<TUser>()要配置 Identity ,只需使用旧式 api :

services.AddIdentity<AppUser, IdentityRole>()
        .AddRoleManager<RoleManager<IdentityRole>>()
        .AddDefaultUI()
        .AddDefaultTokenProviders()
        .AddEntityFrameworkStores<ApplicationDbContext>();

另外,如果您之前已经签过人,请做 先注销再登录 ,它将按预期工作。

[编辑] 对于 ASP.NET Core 3.1,调用 .AddRoles<IdentityRole>() :
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<AppIdentityDbContext>();

然后注销并再次登录。

关于asp.net-core - ASP.NET Core 2.1 标识 : Role-based authorization -> Access Denied,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52531131/

相关文章:

c# - 在 asp.net core 中实现 SOAP 1.2 服务

c# - SignalR : notifying progress of lengthy operation from ASP. NET Core Web API 到 Angular 7 客户端

docker - 是否可以在 IBM Containers for Bluemix 中运行 ASP.NET Core 应用程序?

authorization - 是否可以比较 XACML 策略中的属性?

c# - 具有 2 个前端应用程序(Blazor Server 和 Angular)的项目的建议架构,包括 EFCore、Identity、Mediatr

c# - 更改 Blazor 文件夹给我 "Cannot find the fallback endpoint"

php - Facebook 授权问题

android - 如何将对我的 REST API 的访问限制为仅授权客户端?

asp.net-mvc - AspNet Identity 2.0 电子邮件和用户名重复

c# - 在 ASP.NET 的 IdentityUserRole 2.0 中获取角色名称