授权(角色=“管理员”)在.net core 3.0中不起作用

Str*_*ous 3 asp.net-identity asp.net-core-3.1

我一直在努力解决 .net core 3.0 应用程序中的授权位问题。我的 User.IsInRole("Admin") 返回 true,但如果我将 [Authorize(Roles="Admin")] 添加到控制器,则管理员用户无法访问该页面。这是我的startup.cs文件和控制器中的代码:Startup.cs:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ICanDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ICanDBConnection")));
            var cultureInfo = new CultureInfo("en-GB");
            CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
            CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;

            services.AddIdentity<User, IdentityRole>()
                .AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<ICanDBContext>();

            services.AddAuthorization(options =>
            options.AddPolicy("Role",
                policy => policy.RequireClaim(claimType: ClaimTypes.Role,"Admin")));

            services.AddControllersWithViews(options =>
            {
                var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            });

            services.AddAutoMapper(typeof(Startup));
            services.AddSingleton<IConfiguration>(Configuration);
        }


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseDeveloperExceptionPage();

                //app.UseExceptionHandler("/Home/Error");
            }

            app.UseRouting();
            app.UseStaticFiles();
            app.UseHttpsRedirection();
            
            app.UseAuthorization();
            app.UseAuthentication();

            app.UseEndpoints(endpoints =>
Run Code Online (Sandbox Code Playgroud)

登录页面:

if (!ModelState.IsValid)
            {
                return View(model);
            }

            var user = await _userManager.FindByEmailAsync(model.Email);
            if (user != null && user.IsActive &&
                await _userManager.CheckPasswordAsync(user, model.Password))
            {
                var role = _userManager.GetRolesAsync(user).Result.First();
                var identity = new ClaimsIdentity(IdentityConstants.ApplicationScheme);
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
                identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
                identity.AddClaim(new Claim(ClaimTypes.Role, role));
                await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme,
                    new ClaimsPrincipal(identity));

                return RedirectToLocal(returnUrl);
            }
            else
            {
                ModelState.AddModelError("", "Invalid UserName or Password");
                return View();
            }
Run Code Online (Sandbox Code Playgroud)

我的 AdminController 装饰如下:

[Authorize(Roles = ("Admin"))]
    public class AdminController : Controller
    {
Run Code Online (Sandbox Code Playgroud)

这是 DBContext 类

public partial class StoreDBContext : IdentityDbContext<User, IdentityRole, string>
    {
Run Code Online (Sandbox Code Playgroud)

这是调试模式下的声明值:

在此输入图像描述

HMZ*_*HMZ 7

问题出在Authentication和的顺序上Authorization,在管道中, Authentication应该始终放在 之前Authorization

更多信息:中间件订单