c# - 基于角色的授权属性在 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
}
解决方案
好的,我能够弄清楚,正如 King 所说,我只需要删除我的基本控制器中的 Anonymous 属性。虽然我的主要问题是,当我在 Chrome 中启动的 IIS Express 中运行我的 Web 应用程序时,Windows 身份验证不起作用。所以我需要切换到 IE 或 MS Edge。幸运的是,MS Edge 与 Chrome 非常相似,所以我没有丢失任何我在 Chrome 中需要的 Web 开发工具。
TLDR:Windows 身份验证在 Chrome 中启动的 IIS Express 中不起作用,仅在 IE 和 MS Edge 中起作用。
推荐阅读
- image-processing - 什么是图像处理中的微观结构
- java - Android Studio (Kotlin) 如何存储和部署文件
- python - 有什么方法可以去除骨架的分支吗?
- python - 使用 ffmpeg 到 MP4 的 Dav 不会创建预期的文件
- rust - 如何在结构初始化时运行函数?
- mongodb - MongoDB BI 连接器 ODBC 驱动程序 Power BI 新表未显示在架构中
- python - 如何始终在其所在目录执行 PyInstaller / Platypus 编译的 Python 可执行文件
- function - 当作为另一个 ArrayList 中另一个 PSCustomObject 的属性添加时,PowerShell ArrayList 转换为 PSCustomObject
- php - Symfony 级联持久化或合并复制
- javascript - WebCrypto 在 base64 中生成 ECDSA 签名