【问题标题】:Role returning unauthorized when listed as allowed by the authorize attribute当授权属性允许列出时,角色返回未授权
【发布时间】:2018-08-12 17:16:25
【问题描述】:

我正在尝试使用 Identity and Entity Frame Work 向我的 ASPDotNet Core 项目添加管理员角色。 目标是让管理员访问视图/控制器,这将允许他们对普通用户无法访问的网站进行更改。

这是我用来创建角色、超级用户和为数据库播种的代码(稍后我可能会创建一个种子数据库类,但我会专注于让基础知识先发挥作用)。这段代码目前存在于我的启动类中。在 configure 方法中调用 CreateSuperUser。

private async Task CreateSuperUser(IServiceProvider serviceProvider)
    {
        var _roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
        var _userManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>();  
        IdentityResult result;

        var doesAdminRoleExist = await _roleManager.RoleExistsAsync("AdminRole");
        var doesBasicRoleExist = await _roleManager.RoleExistsAsync("BasicRole");

        if (!doesAdminRoleExist)
        {

            IdentityRole AdminRole = new IdentityRole("AdminRole");
            result = await _roleManager.CreateAsync(AdminRole);
            IdentityUser SuperUser = new IdentityUser() { Email = "superuser@superuser.com", PasswordHash = "SecureP@ssword!1234", UserName = "superuser@superuser.com", };
            var createSuperUser = await _userManager.CreateAsync(SuperUser, SuperUser.PasswordHash);
            if (createSuperUser.Succeeded)
            {
                await _userManager.AddToRoleAsync(SuperUser, AdminRole.Name);

            }
        }

        if (!doesBasicRoleExist)
        {
            IdentityRole BasicRole = new IdentityRole("BasicRole");
            result = await _roleManager.CreateAsync(BasicRole);
        }

    }

在我的控制器类中,我请求这样的授权

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

        return View();
    }

我可以使用 superUser@superuser.com 登录没有问题,但是当我尝试单击联系链接时,它告诉我我无权访问此资源。 我根本无法弄清楚如何正确创建这个自定义角色。我的具体问题是: 谁能帮我找出我的流程中阻止我按角色授权的错误

我花了很多时间阅读堆栈溢出、google 和 Microsoft 文档,所以请不要建议。我的方法非常基于此处对其他用户的答案之一,Microsoft 文档是我桌面上的 PDF。

我是编程新手,无法掌握所有内容。尤其是 2.0 和 2.1 的差异。更不用说框架 4.6 了。

我为这篇冗长的帖子道歉。提前感谢您的帮助。

附带说明,这是我的配置方法,以防万一。我还从 nuget 的控制台运行了 add-migration/update-database。

 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>();
        services.AddAuthentication();
        services.AddAuthorization();
        services.AddMvc();

    }

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();

        CreateSuperUser(serviceProvider).Wait();

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

【问题讨论】:

    标签: c# entity-framework asp.net-core-mvc authorization asp.net-identity


    【解决方案1】:

    这是一个跟踪 UserRoles in DefaultIdentity #1813 的错误。

    如需解决方法,请更改您的代码,如下所示

            //services.AddDefaultIdentity<IdentityUser>()
            //    .AddEntityFrameworkStores<ApplicationDbContext>();
            //services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>()
            //    .AddEntityFrameworkStores<ApplicationDbContext>()
            //    ;
            services.AddIdentity<IdentityUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultUI()
            .AddDefaultTokenProviders();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    

    此问题已在 release/2.2 中修复,该问题已被跟踪 Fix issue with role claim missing in AddIdentityCore #1832

    注意,如果上面的代码不适合你,你可能需要注销并登录,因为这个身份是由Cookies保存的。

    【讨论】:

    • 这非常有效。我不知道应该为解决方案的简单性而笑还是哭。我花了很多时间试图找出问题所在。我非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-03
    • 2013-12-03
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多