【发布时间】:2017-03-06 04:39:03
【问题描述】:
我有一个 OWIN 托管的 web api,它以 Network Service 运行,WindowsAuthentication 通过 OWIN Startup 类的 Configuration 方法中的以下行启用。
HttpListener listener = (HttpListener)appBuilder.Properties["System.Net.HttpListener"];
listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;
一切正常,除非我尝试获取用户详细信息,通过
-
caller = System.Security.Principal.WindowsIdentity.GetCurrent();
返回:AuthenticationType: "Negotiate", Name: "NT AUTHORITY\NETWORK SERVICE" -
ApiController.User.Identity
返回:AuthenticationType: "NTLM", Name: "Domain\Username"
我实际上期待ApiController.User.Identity 提供的凭据。我很困惑为什么我在两者中都得到了不同的结果。谁能帮我这个?
public class CustomFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var caller = OperationContext.Current; //null
caller = System.Web.HttpContext.Current; //null
caller = actionContext.RequestContext.Principal.Identity as WindowsIdentity; //desired
caller = System.Security.Principal.WindowsIdentity.GetCurrent(); //gives account details under which the project is hosted.
}
}
OWIN 启动类:
public class Startup
{
public void Configuration(IAppBuilder appBuilder)
{
HttpConfiguration config = new HttpConfiguration();
HttpListener listener = (HttpListener)appBuilder.Properties["System.Net.HttpListener"];
listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;
config.MapHttpAttributeRoutes();
config.MapODataServiceRoute(
routeName: "ODataRoute",
routePrefix: "Data",
model: GetModel()
);
config.EnsureInitialized();
appBuilder.UseWebApi(config);
}
}
【问题讨论】:
-
在 IIS 中运行 Web API 项目的用户帐户与登录到您的应用程序并调用 API 的用户不同。这就是为什么你在那里得到不同的价值。如果您想了解调用 Web API 的用户的详细信息,那么您应该使用
ApiController.User.Identity。 -
谢谢。那么如果我想在 ActionFilter 中获取这些详细信息呢?
-
在 Action 过滤器中你应该可以访问 controllerContext 或者你可以简单地做
Request.User.Identity。 -
var caller = actionContext.RequestContext.Principal.Identity as WindowsIdentity;这工作正常。
标签: c# asp.net-web-api2 windows-authentication ntlm network-service