簡體   English   中英

基於角色的授權屬性在 ASP.NET Core MVC 中不起作用

[英]Role based authorization attribute not working in ASP.NET Core MVC

我正在嘗試在 ASP.NET Core MVC 中構建一個應用程序,並使用基於角色的授權和 windows 身份驗證。

即使我在我的基礎 controller 上添加了 HttpContext 中的所有角色,但在我的帳戶沒有所需角色的情況下導航到 controller 時,它仍然不會引發未授權提示/錯誤。

我在想的唯一問題可能是我沒有在 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?}");
    });
}           

然后我的基礎 controller class:

[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 function:

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

我的 controller 具有授權屬性:

    [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
}

好的,我能夠弄清楚,正如 King 所說,我只需要刪除我的基礎 controller 中的匿名屬性。 雖然我的主要問題是,當我在 Chrome 中啟動的 IIS Express 中運行我的 web 應用程序時,Windows 身份驗證不起作用。 所以我需要切換到 IE 或 MS Edge。 幸運的是,MS Edge 與 Chrome 非常相似,所以我沒有丟失任何我在 Chrome 中需要的 web 開發工具。

TLDR:Windows 身份驗證在 Chrome 中啟動的 IIS Express 中不起作用,僅在 IE 和 MS Edge 中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM