我正在尝试学习如何使用IClaimsTransformation
来修改Windows身份验证中的用户声明。但是当我尝试使用它时,出现错误消息
“ InvalidOperationException:未指定authenticationScheme,并且未找到DefaultChallengeScheme。”
我主要是在Mac上尝试它,但是我也在公司域中的公司PC中尝试过。他们两个都给我同样的错误。我也是IIS Express(VS和Rider的调试模式)。
在我的启动文件中
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSingleton<IClaimsTransformation, UserClaims>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
我有这个类来进行索赔转换
public class UserClaims: IClaimsTransformation
{
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
var ci = (ClaimsIdentity) principal.Identity;
var c = new Claim(ci.RoleClaimType, "Admin");
ci.AddClaim(c);
return Task.FromResult(principal);
}
}
也将此装饰器用作我的控制器
[Authorize(Roles = "Admin")]
答案 0 :(得分:0)
“ InvalidOperationException:未指定authenticationScheme,并且未找到DefaultChallengeScheme。”
几个月前我使用Windows身份验证时遇到了同样的问题。原来我没有启用Windows Authentication
。
请检查“属性/调试”选项卡,并确保选中Enable Windows Authentication
:
作为旁注,您正在修改原始 principal
。 IMO,最好返回全新主体:
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal) { var cp = principal.Clone(); // create a copy var ci = (ClaimsIdentity)cp.Identity; var c = new Claim(ci.RoleClaimType, "Admin"); ci.AddClaim(c); // modify the copy return Task.FromResult(cp); }
答案 1 :(得分:0)
首先,使用Rider作为IDE弄乱了我的调试设置,在删除了演示应用程序并将调试设置恢复为默认的IIS Express设置之后,我设法使代码正常工作。
此后,每次尝试调试应用程序时,我都遇到403错误,并在@itminus的帮助下,按中间件顺序发现了问题。我在UseAuthentication()上使用UseAuthorization(),这是我的错误。因此,将UseAuthentication()放在UseAuthorization()上解决了我的第二个问题。