Mr *_*ies 7 c# asp.net-web-api asp.net-core-mvc asp.net-core
在 Windows 上运行的 ASP.NET 核心 (2.1) 中,我使用配置了以下身份验证方案的 HttpSys:
builder.UseHttpSys(options =>
{
options.Authentication.Schemes = AuthenticationSchemes.Negotiate | AuthenticationSchemes.NTLM;
options.Authentication.AllowAnonymous = true;
})
Run Code Online (Sandbox Code Playgroud)
然后在我的 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....
}
});
});
Run Code Online (Sandbox Code Playgroud)
这个例子有点粗俗,但重点是 context.User.Identity.Name 总是空的,我希望看到正在进行调用的 AD 帐户的名称。请注意,调用是在 powershell 中完成的,如下所示:
Invoke-WebRequest -Uri http://localhost:5555/sensitiveOperation -Method Put -UseDefaultCredentials
Run Code Online (Sandbox Code Playgroud)
我可以将此代码放在控制器中并使用 [Authorize] 属性来获取凭据,但我更愿意在点击 Mvc 管道之前执行此操作。有没有办法在管道的早期阶段获得用户?
更改允许匿名
options.Authentication.AllowAnonymous = false;
Run Code Online (Sandbox Code Playgroud)
如果您启用了匿名,并且您没有提示进行身份验证,那么浏览器将不会进行身份验证。即使您确实发送创建,asp.net 也不会获取它们,除非控制器/方法上有 Authenticate 属性,或者,如果您要使用函数路由,则调用 signin。
如果您不想设置AllowAnonymous为false,您可以尝试context.ChallengeAsync基于 来验证请求Credential。
这是代码:
app.MapWhen(context => context.Request.Path.Equals("/sensitiveOperation") && context.Request.Method.Equals(HttpMethods.Put), subApp =>
{
subApp.Run(async (context) =>
{
var authService = context.RequestServices.GetRequiredService<IAuthorizationService>();
if (!context.User.Identity.IsAuthenticated)
{
//await context.ChallengeAsync("Windows"); //Option1
//await context.ChallengeAsync(); //Option2
await context.ChallengeAsync(HttpSysDefaults.AuthenticationScheme); //Option3
}
if (context.User.Identity.Name == "admin")
{
await context.Response.WriteAsync("Performing sensitive operation.");
// .. Do Sensitive operation....
}
});
});
Run Code Online (Sandbox Code Playgroud)
请注意,对于这种方式,subApp.Run将运行两次,第一个请求是未经身份验证的,它将挑战凭证,第二个请求是经过身份验证的并且context.User.Identity.Name将具有价值。这个过程是后端的,不会体现在powershell.
| 归档时间: |
|
| 查看次数: |
4946 次 |
| 最近记录: |