简体   繁体   English

如何在 core2.2 mvc 项目中使用 IClaimsTransformation

[英]how to use IClaimsTransformation in core2.2 mvc project

I am trying to learn how to use IClaimsTransformation to modify users claims in windows authentication.我正在尝试学习如何使用IClaimsTransformation来修改 windows 身份验证中的用户声明。 But when I try to use it I get an error saying但是当我尝试使用它时,我收到一条错误消息

"InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found." “InvalidOperationException:没有指定 authenticationScheme,也没有找到 DefaultChallengeScheme。”

I am mainly trying it on mac but also I tried in my company pc in company domain.我主要在mac上尝试它,但我也在公司域的公司电脑上尝试过。 Both of them gives me the same error.他们都给了我同样的错误。 Also I am IIS express (debug mode from both VS and Rider).我也是 IIS express(来自 VS 和 Rider 的调试模式)。

in my startup file在我的启动文件中

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?}");
        });



    }

and I have this class for claims transformation我有这个 class 用于索赔转换

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);
    }
}

also using this decorator for my controller也为我的 controller 使用这个装饰器

[Authorize(Roles = "Admin")]

First of all using Rider as an IDE messed up my debug settings and after deleting the demo app and restoring the debug settings to default IIS Express settings I managed to get my code working.首先,使用 Rider 作为 IDE 搞砸了我的调试设置,在删除演示应用程序并将调试设置恢复为默认 IIS Express 设置后,我设法让我的代码正常工作。

After that I had an 403 error every time I tried to debug my application and with the help of @itminus we found the the problem in my middlewares order.之后,我每次尝试调试应用程序时都会遇到 403 错误,在@itminus 的帮助下,我们在中间件订单中发现了问题。 I was using UseAuthorization() over the UseAuthentication() and that was my mistake.我在 UseAuthentication() 上使用 UseAuthorization() ,这是我的错误。 So putting UseAuthentication() over the UseAuthorization() solved my second problem.所以将 UseAuthentication() 放在 UseAuthorization() 上解决了我的第二个问题。

"InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found." “InvalidOperationException:没有指定 authenticationScheme,也没有找到 DefaultChallengeScheme。”

I got the same issue when I used Windows Authentication several months ago.几个月前我使用 Windows 身份验证时遇到了同样的问题。 It turns out I didn't enable the Windows Authentication .原来我没有启用Windows Authentication

Please check the Properties/Debug tab, and make sure the Enable Windows Authentication is checked:请检查属性/调试选项卡,并确保选中Enable Windows Authentication

在此处输入图像描述


As a side note, you're modifying the original principal .作为旁注,您正在修改原始principal IMO, returning a brand new principal is preferred: 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);                          
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当FromBody MVC Core2.2剂量工作时出现错误请求 - Bad Request whenFromBody mvc core2.2 dosent work .Net Core2.2:如何在EF Codefirst方法中更改字符集 - .Net Core2.2 : how to change characterset in EF codefirst approach 如何在ASP.Net Core2.2中覆盖415响应 - How to Override 415 response in ASP.Net Core2.2 EF Core2.2:Scaffold-DbContext无法在WPF项目中使用命名连接字符串 - EF Core2.2: Scaffold-DbContext not working with named connection string in WPF project 如何使用 articleName=sample-article-name [MVC Core2.2] 将“www.example.com/sample-article-name”路由到 RazorPage Index.cshtmll - How to route to "www.example.com/sample-article-name" to RazorPage Index.cshtmll with articleName=sample-article-name [MVC Core2.2] 无法使用 Firefox 调试某些 asp.net core2.2 网页。 如何使用 Firefox 进行调试? - Unable to debug some asp.net core2.2 web pages with Firefox. How can I debug with Firefox? 尽管我具有.NET core 2.2,但如何打开.NET core 2.0 mvc项目? - How can I open a .NET core 2.0 mvc project despite that I have .NET core 2.2? 使用 ASP.NET Core2.2 中的 CancellationToken 取消内部任务 - Cancel an internal task using CancellationToken in ASP.NET Core2.2 使用HttpClient Alwyes Null ASP.net Core2.2将IFormFile发送到API - Send IFormFile To API using HttpClient Alwyes Null ASP.net Core2.2 无法使用 dinktopdf 为 .net core2.2 azure functionapp 加载 dll libwkhtmltox - Unable to load the dll libwkhtmltox using dinktopdf for a .net core2.2 azure functionapp
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM