首页 > 解决方案 > 基于角色的授权属性在 ASP.NET Core MVC 中不起作用

问题描述

我正在尝试在 ASP.NET Core MVC 中构建一个应用程序,并使用基于角色的授权和 Windows 身份验证。

即使我在基本控制器上的 HttpContext 中添加了所有角色,但在我的帐户没有所需角色的情况下导航到控制器时,它仍然不会引发未授权提示/错误。

我在想的唯一问题可能是我没有在 Startup.cs 上正确配置授权?

这是我的启动配置服务:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<CimsDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyDatabase")));

    services.AddControllersWithViews();
    services.AddDistributedMemoryCache();
    services.AddAuthentication(IISDefaults.AuthenticationScheme);
    services.AddAuthorization();


    services.AddSingleton(Configuration);
    services.AddSession(options =>
    {
        options.Cookie.Name = ".MySession";
        options.IdleTimeout = TimeSpan.FromMinutes(Convert.ToDouble(Configuration.GetSection("inMinutes").Value));
        options.Cookie.HttpOnly = true;
        options.Cookie.IsEssential = true;
    });
}

这是我的启动配置:

public void Configure(IApplicationBuilder app)
{
    if (_env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseSession();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}           

然后我的基本控制器类:

[AllowAnonymous]
public class AppSessionController : Controller
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (HttpContext.User.Identity.IsAuthenticated)
        {
            //no valid session / create new session
            if (String.IsNullOrEmpty(HttpContext.Session.GetString(AppSessionIdentifier.IsAlive)))
            {
                //initialize new user identity
                HttpContext.User = UserIdentity.NewUserIdentity(config, HttpContext);
            }
        }
        base.OnActionExecuting(filterContext);
    }
}

接下来是我的 NewUserIdentity 函数:

public static GenericPrincipal NewUserIdentity(IConfiguration config, HttpContext httpContext)
{
    
    string AccountName = httpContext.User.Identity.Name.Split('\\')[1];
    string Env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

    List<string> roles = new List<string>();
    if (ADHelper.IsInGroup(AccountName, config.GetSection($"ADGroupRoles:{Env}:ReadOnly").Value))
        roles.Add(Roles.ReadOnly.ToString());
    if(ADHelper.IsInGroup(AccountName, config.GetSection($"ADGroupRoles:{Env}:Admin").Value))
        roles.Add(Roles.Admin.ToString());

    return new GenericPrincipal(new GenericIdentity(AccountName), roles.ToArray());
}

我的具有 Authorize 属性的控制器:

    [Authorize(Roles = "ReadOnly")]
    public class MatterController : AppSessionController
    {
        [Authorize(Roles = "ReadOnly")]
        public ActionResult Details(int matterId)
        {
            return View();
        }
   }

我的角色枚举:

public enum Roles
{
    [Description("ReadOnly")]
    ReadOnly = 1,

    [Description("Administrator")]
    Admin = 4
}

标签: c#asp.net-mvcasp.net-core

解决方案


好的,我能够弄清楚,正如 King 所说,我只需要删除我的基本控制器中的 Anonymous 属性。虽然我的主要问题是,当我在 Chrome 中启动的 IIS Express 中运行我的 Web 应用程序时,Windows 身份验证不起作用。所以我需要切换到 IE 或 MS Edge。幸运的是,MS Edge 与 Chrome 非常相似,所以我没有丢失任何我在 Chrome 中需要的 Web 开发工具。

TLDR:Windows 身份验证在 Chrome 中启动的 IIS Express 中不起作用,仅在 IE 和 MS Edge 中起作用。


推荐阅读