ASP.NET Core 2.1 Web API基于AD授权配置后运行dotnet run报错求助
问题分析与解决方案
你遇到的异常是因为使用dotnet run启动时,程序用的是Kestrel服务器,而当前配置仅针对IIS托管环境的Windows认证,Kestrel缺少对应的认证方案配置,导致无法找到默认的认证/挑战方案。
1. 修复认证配置(解决异常)
修改Startup.cs中的ConfigureServices方法,为Kestrel和IIS都配置Windows认证,并设置默认方案:
using Microsoft.AspNetCore.Authentication.Windows; public void ConfigureServices(IServiceCollection services) { services.AddDbContext<AppDbContext>(options => options.UseSqlite(Configuration.GetConnectionString("DefaultConnection"))); // 配置Windows认证,同时支持IIS和Kestrel services.AddAuthentication(options => { options.DefaultAuthenticateScheme = WindowsDefaults.AuthenticationScheme; options.DefaultChallengeScheme = WindowsDefaults.AuthenticationScheme; }) .AddWindows(); // 添加Windows认证处理程序,支持Kestrel环境 services.AddAuthorization(options => { options.AddPolicy("L1-Users", policy => policy.RequireRole("Ad-L1-Users")); options.AddPolicy("L2-Users", policy => policy.RequireRole("Ad-L2-Users")); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
如果项目未引用Microsoft.AspNetCore.Authentication.Windows包,需要通过NuGet安装:
dotnet add package Microsoft.AspNetCore.Authentication.Windows
2. 处理AD组到角色声明的映射
Windows认证默认会将AD组的SID作为GroupSid声明返回,但你的授权策略是基于组名的,因此需要将SID转换为对应的AD组名,并添加到Role声明中:
步骤1:添加Claims转换类
创建ClaimsTransformer.cs文件:
using System.Security.Claims; using System.Security.Principal; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; public class ClaimsTransformer : IClaimsTransformation { public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal) { var identity = (ClaimsIdentity)principal.Identity; // 获取所有组SID声明 var groupSids = identity.Claims.Where(c => c.Type == ClaimTypes.GroupSid); foreach (var sidClaim in groupSids) { try { // 将SID转换为AD组名 var groupSid = new SecurityIdentifier(sidClaim.Value); var groupName = groupSid.Translate(typeof(NTAccount)).Value; // 添加组名作为Role声明 identity.AddClaim(new Claim(ClaimTypes.Role, groupName)); } catch { // 忽略无法转换的SID(如系统内置组) } } return Task.FromResult(principal); } }
步骤2:注册Claims转换服务
在Startup.cs的ConfigureServices中添加:
services.AddScoped<IClaimsTransformation, ClaimsTransformer>();
3. 接口授权配置
根据需求为不同接口添加对应授权特性:
- 对所有内网用户开放:使用
[Authorize](确保用户经过Windows认证,仅内网AD用户可访问) - 仅限Ad-L1-Users组:
[Authorize(Policy = "L1-Users")] - 仅限Ad-L2-Users组:
[Authorize(Policy = "L2-Users")]
4. 本地开发测试注意事项
- 使用
dotnet run启动时,确保你当前登录的Windows账号属于对应的AD组,否则会被拒绝访问 - 如果需要在Visual Studio Code中调试,确保launch配置使用正确的profile
内容的提问来源于stack exchange,提问作者Mandar Patil
相关产品推荐
相关产品推荐

