c# - 访问 ASP.NET Core 中间件中的用户凭据

标签 c# asp.net-web-api asp.net-core asp.net-core-mvc

在 ASP.NET core (2.1) 中,在 Windows 上运行,我使用配置了以下身份验证方案的 HttpSys:

builder.UseHttpSys(options =>
        {
            options.Authentication.Schemes = AuthenticationSchemes.Negotiate | AuthenticationSchemes.NTLM;
            options.Authentication.AllowAnonymous = true;
        })

然后在我的 Startup.Configure() 方法中,我尝试访问调用 uri“/sensitiveOperation”的客户端的用户凭据,如下所示:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseAuthentication();

        app.MapWhen(context => context.Request.Path.Equals("/sensitiveOperation") && context.Request.Method.Equals(HttpMethods.Put), subApp =>
        {                
            subApp.Run(async (context) =>
            {
                if (context.User.Identity.Name == "admin")
                {
                    await context.Response.WriteAsync("Performing sensitive operation.");
                    // .. Do Sensitive operation....
                }                    
            });
        });

这个例子有点粗俗,但要点是 context.User.Identity.Name 始终为空,我希望看到正在进行调用的 AD 帐户的名称。请注意,调用是在 powershell 中完成的,如下所示:

Invoke-WebRequest -Uri http://localhost:5555/sensitiveOperation -Method Put -UseDefaultCredentials

我可以将此代码放入 Controller 中并使用 [Authorize] 属性来获取凭据,但我更愿意在访问 Mvc 管道之前执行此操作。有没有办法让用户处于管道的早期阶段?

最佳答案

更改允许匿名

options.Authentication.AllowAnonymous = false;

如果您启用了匿名,并且没有提示进行身份验证,则浏览器将不会进行身份验证。即使您确实发送创建,asp.net 也不会获取它们,除非 Controller /方法上有 Authenticate 属性,或者,如果您要使用函数路由,则调用登录。

关于c# - 访问 ASP.NET Core 中间件中的用户凭据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51844740/

相关文章:

c# - StatusCodeResult 或 ResponseMessageResult

c# - 在 ASP.NET Core WebAPI 中实现 JSON 合并补丁

asp.net - 将 OData 与 Web API 结合使用有什么优势?

angularjs - PUT/DELETE 在 VS Community 2015 中使用 Angular 和 WebAPI 给出 ​​405 错误

asp.net-core - 如何在ASP.NET Core中启动Quartz?

c# - 带有 IHtmlHelper 引用的自定义 Razor 助手

c# - 如何确定是否安装了 .NET Core

c# - 在MVC中调用存储过程

c# - 应用程序域刷新/重启

javascript - Nancy 响应未返回 index.html 的正确 MIME 类型,包括