简体   繁体   English

ASP.NET Core 2.1:Razor Pages - 基于角色的授权不起作用

[英]ASP.NET Core 2.1: Razor Pages - role based authorisation not working

My Razor Pages app is configured as follows.我的 Razor Pages 应用程序配置如下。 Startup.cs contains: 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.UseSqlite(
            Configuration.GetConnectionString("DefaultConnection")));

    services.AddDefaultIdentity<IdentityUser>()
        .AddRoles<IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>();
    
    services.AddAuthorization(options =>
    {
        options.AddPolicy("RequireAdminRole", policy => 
            policy.RequireAuthenticatedUser().RequireRole("Admin"));
    });

    services.AddMvc()
        .AddRazorPagesOptions(options =>
        {
            options.Conventions.AuthorizePage("/About", "RequireAdminRole");
        })
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

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

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();
    app.UseAuthentication();
    app.UseMvc();
}

I have a user with the "Admin" role.我有一个具有“管理员”角色的用户。 When the user is logged in and accesses the "About" page, I get the following:当用户登录并访问“关于”页面时,我得到以下信息:

Access denied拒绝访问

You do not have access to this resource.您无权访问此资源。

What am I doing wrong?我究竟做错了什么?

UPDATE更新

If I remove the AuthorizePage and use GetUsersInRoleAsync("Admin") in the About.cshtml.cs page OnGet method, then output the UserName property in the About.cshtml page, the admin user is displayed.如果我删除AuthorizePage和使用GetUsersInRoleAsync("Admin")About.cshtml.cs页面OnGet方法,然后输出UserName在属性About.cshtml页,显示管理员用户。 So, not sure why the AuthorizePage is not working.所以,不确定为什么AuthorizePage不起作用。

UPDATE 29-May-2017 2017 年 5 月 29 日更新

My source code is in thisGithub Resository我的源代码在这个Github 资源库中

I've managed to find the solution:我设法找到了解决方案:

services.AddIdentity<IdentityUser, IdentityRole>()
.AddDefaultUI()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();

I think it works as follows:我认为它的工作原理如下:

  • AddItentity - Sets up identity. AddItentity - 设置身份。
  • AddDefaultUI - Use new Razor Class Library UI. AddDefaultUI - 使用新的 Razor 类库 UI。
  • AddDefaultTokenProviders - Needed for two factor authentication. AddDefaultTokenProviders - 需要两因素身份验证。

You must put .UseAuthentication() before .UseMvc() app.UseAuthentication(); app.UseMvc();你必须把.UseAuthentication()之前.UseMvc() app.UseAuthentication(); app.UseMvc(); app.UseAuthentication(); app.UseMvc(); I lost a lot of hair because of this.因为这个,我掉了很多头发。

Please change these lines of your code and try again.请更改这些代码行,然后重试。 Thank you谢谢

        //Old
        /*services
            .AddDefaultIdentity<IdentityUser>()
            .AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();
            */

        //New
        services
            .AddIdentity<IdentityUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();

The above answers did not work for me but after reading this on Github i changed the code from using Alan T's solution.上述答案对我不起作用,但在Github上阅读本文后,我更改了使用 Alan T 解决方案的代码。

services.AddIdentity<IdentityUser, IdentityRole>()
 .AddDefaultUI()
 .AddDefaultTokenProviders()
 .AddEntityFrameworkStores<ApplicationDbContext>();

To this对此

  services.AddIdentity<IdentityUser, IdentityRole>()
             .AddEntityFrameworkStores<AuthenticationContext>()
          .AddDefaultUI();

the .AddEntityFrameworkStores<AuthenticationContext>() needs to come after the services.AddIdentity<IdentityUser, IdentityRole>() .AddEntityFrameworkStores<AuthenticationContext>()需要跟在services.AddIdentity<IdentityUser, IdentityRole>()

It works perfectly.它完美地工作。 I am not using TWO factor authentication so i dont need the .AddDefaultTokenProviders()我没有使用双因素身份验证,所以我不需要.AddDefaultTokenProviders()

Hopefully it will help someone else who had the same issue i had with roles.希望它会帮助其他与我在角色上遇到相同问题的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM