我正在开发 ASP.NET Core Web 应用程序 (.NET 5.0)。
这是一个 Intranet 应用程序,因此我使用 Windows 身份验证。
对于授权,我使用 AspNetCore.Identity 中的自定义角色(出于各种原因不想使用 AD 组)。
我正在使用IClaimsTransformation
类来实现TransformAsync
方法,以便将我的自定义角色添加到用户的声明中。
我添加了[Authorize(Roles = "Admin")]
在控制器上测试整个方案。
当我在调试(IIS Express)中测试时,TransformAsync
方法永远不会被调用。
我确实检查了我的 IIS 中是否启用了 Windows 身份验证launchSettings.json
:
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
"iisExpress": {
"applicationUrl": "http://localhost:49861",
"sslPort": 44307
}
我还检查了是否为调试模式启用了 windowsAuthentication (IIS Express):在此输入图像描述 https://i.stack.imgur.com/XP3hX.png
下面是我的ConfigureServices
方法 (startup.cs
) :
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>
(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllersWithViews();
// Windows Authentication
services.AddAuthentication(IISDefaults.AuthenticationScheme);
// Claim transformation
services.AddScoped<IClaimsTransformation, AddRolesClaimsTransformation>();
//ASP Identity
services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();
}
这是我的Configure
方法 (startup.cs
) :
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Event}/{action=Dashboard}/{id?}");
});
}
这是TransformAsync
方法 :
public class AddRolesClaimsTransformation : IClaimsTransformation
{
private readonly UserManager<ApplicationUser> _userManager;
public AddRolesClaimsTransformation(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
//code removed for simplicity - this never gets called
}
}
我尝试更改顺序services.AddAuthentication(IISDefaults.AuthenticationScheme)
in startup.cs
如本中所建议的post https://stackoverflow.com/questions/65167381/iclaimstransformation-not-firing但这并没有解决问题。
我缺少什么?