授权(角色 = "Admin")在 .net 核心 3.0 中不起作用

Authorize(Roles = "Admin") not working in .net core 3.0

我一直在努力解决我的 .net core 3.0 应用程序中的授权位问题。我的 User.IsInRole("Admin") returns 是的,但如果我将 [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 =>

登录页面:

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

我的 AdminController 装饰成这样:

[Authorize(Roles = ("Admin"))]
    public class AdminController : Controller
    {

这是 DBContext class

public partial class StoreDBContext : IdentityDbContext<User, IdentityRole, string>
    {

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

问题出在管道中 AuthenticationAuthorization 的顺序, Authentication 应始终放在 Authorization.

之前

更多信息:Middleware Order

你应该更改认证位置,在授权后进行