ASP.NET Core 2.2授权角色不起作用的属性

时间:2019-06-08 22:07:46

标签: c# asp.net-core roles asp.net-core-2.2 authorize-attribute

我正在将ASP.NET 4.6 MVC应用程序迁移到Asp.Net Core 2.2。我已经设法迁移了所有数据。我已经检查了AspNetUsers,AspNetRoles和AspNetUserRoles表,它们具有已迁移的数据。我根据官方文档使用Razor类库搭建了Login和AccessDenied页面

[https://docs.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-2.2&tabs=visual-studio]

我的情况如下:我有一个名为Leads的控制器,该控制器有一个名为Create的动作。我只希望那些属于CreateLead角色的用户访问Create操作。为了进行测试,我将其配置为默认页面,因此,在应用程序启动时,它将把用户重定向到“登录”页面,因为该操作受Authorize属性的保护。如果用户通过了身份验证,他们将被重定向到Leads contoller。

我可以使用存储在AspNetUsers表中的用户名和密码成功登录。如果我添加Authorize属性而没有指定 Role 属性,并且没有在Startup类中添加AddRoles扩展名,我将被重定向到“创建”视图成功。

 [Authorize]
 public IActionResult Create()
 {
     return View();
 }

启动类

services.AddDefaultIdentity<User>()
      .AddEntityFrameworkStores<SalesIdentityContext>();

但是,如果我指定 Roles属性并将AddRoles扩展名添加到Startup类,则如下所示,浏览器将不会加载视图。它给了我以下错误:https://localhost:44388/处的网页可能被暂时关闭,或者已永久移至新的网址:ERR_SPDY_PROTOCOL_ERROR。

[Authorize( Roles = "CreateLead")]
public IActionResult Create()
{
    return View();
}

启动类:

public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddDbContext<SalesIdentityContext>(options =>
         options.UseSqlServer(Configuration.GetConnectionString("IdentityConnection")));

        services.AddDefaultIdentity<User>()
            .AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<SalesIdentityContext>();

        services.ConfigureApplicationCookie(options =>
        {
            // Cookie settings
            options.Cookie.HttpOnly = true;
            options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
            options.LoginPath = "/Identity/Account/Login";
            options.AccessDeniedPath = "/Identity/Account/AccessDenied";
            options.SlidingExpiration = true;
        });

        // Add application services.
        services.AddScoped(typeof(IAppLogger<>), typeof(LoggerAdapter<>));
        services.AddScoped<ILeadService, LeadService>();

        services.AddHttpClient("my_api_client_name", c => 
        {
            c.BaseAddress = "my_api_uri");
        });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            ListAllRegisteredServices(app);
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            //app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();
        app.UseAuthentication();
        app.UseMvc(routes =>
        {
            routes.MapRoute(name: "default", template: "{controller=Leads}/{action=Create}/{id?}");
        });
    }

我有一个名为User的自定义标识类,它正在扩展IdentityUser类。在User类上,我添加了FirstName和LastName属性。

我已经检查了AspNetUserRoles表,并可以确认UserId和RoleId均可用。

Visual Studio输出 Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler:信息:AuthenticationScheme:Identity.Application已登录。 WebApp.Areas.Identity.Pages.Account.LoginModel:Information:用户已登录。 Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker:Information:执行的处理程序方法OnPostAsync,返回结果Microsoft.AspNetCore.Mvc.LocalRedirectResult。 Microsoft.AspNetCore.Mvc.Infrastructure.LocalRedirectResultExecutor:信息:执行LocalRedirectResult,重定向到/。 Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker:信息:执行的页面/帐户/登录时间为10100.4486ms Microsoft.AspNetCore.Routing.EndpointMiddleware:Information:执行的端点'Page:/ Account / Login' Microsoft.AspNetCore.Hosting.Internal.WebHost:信息:请求在10232.1354ms中完成302

2 个答案:

答案 0 :(得分:0)

您可以添加

app.UseAuthorization();

  app.UseAuthentication();

答案 1 :(得分:-1)

在addmvc之后您缺少addauthorization。在“配置服务方法”中,进行如下更改: services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddAuthorization();

相关问题