首页 > 解决方案 > 如何在 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")]

标签: c#asp.net-core.net-coreasp.net-core-mvcasp.net-core-2.2

解决方案


首先,使用 Rider 作为 IDE 弄乱了我的调试设置,在删除演示应用程序并将调试设置恢复为默认的 IIS Express 设置后,我设法让我的代码正常工作。

之后,我每次尝试调试应用程序时都会遇到 403 错误,在@itminus 的帮助下,我们在中间件订单中发现了问题。我在 UseAuthentication() 上使用 UseAuthorization() ,这是我的错误。所以将 UseAuthentication() 放在 UseAuthorization() 上解决了我的第二个问题。


推荐阅读