c# - 如何在 core2.2 mvc 项目中使用 IClaimsTransformation
问题描述
我正在尝试学习如何IClaimsTransformation
在 Windows 身份验证中使用来修改用户声明。但是当我尝试使用它时,我收到一条错误消息
“InvalidOperationException:没有指定 authenticationScheme,也没有找到 DefaultChallengeScheme。”
我主要在mac上尝试它,但我也在公司域的公司电脑上尝试过。他们都给了我同样的错误。我也是 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")]
解决方案
首先,使用 Rider 作为 IDE 弄乱了我的调试设置,在删除演示应用程序并将调试设置恢复为默认的 IIS Express 设置后,我设法让我的代码正常工作。
之后,我每次尝试调试应用程序时都会遇到 403 错误,在@itminus 的帮助下,我们在中间件订单中发现了问题。我在 UseAuthentication() 上使用 UseAuthorization() ,这是我的错误。所以将 UseAuthentication() 放在 UseAuthorization() 上解决了我的第二个问题。
推荐阅读
- javascript - Node.js 服务器未发送响应,或客户端未接收
- deep-learning - 回归器的初始化是什么?
- vb.net - 有没有一种方法可以使用 WebRequest 类在 80 以外的另一个端口上查询服务器?
- jquery - 如何让用户从下拉菜单中只选择一个选项?
- python - 将程序添加到 PATH 有什么意义?
- php - centOS 7上缺少Nginx default.conf
- javascript - 从 p:selectedCheckbox javascript 获取值复选框
- python - 计算字符串在特定列中出现的次数
- java - OptaPlanner 7.21.0 无法从 jar 文件执行 - 目录 dataDir 错误
- python - 将 Flask 配置导入非 Flask 脚本的最佳方法是什么?