ApiController.User.Identity和System.Security.Principal.WindowsIdentity提供不同的用户详细信息

时间:2017-03-06 04:39:03

标签: c# asp.net-web-api2 windows-authentication ntlm network-service

我有一个OWIN托管的web api,它运行为Network Service,并在OWIN Startup类的Configuration方法中由以下行启用WindowsAuthentication

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

    }
}

1 个答案:

答案 0 :(得分:2)

这里有清楚的解释 - https://msdn.microsoft.com/en-us/library/aa302377.aspx

  

ASP.NET提供以下主体和标识对象   实现:

     

  • WindowsPrincipal 和    WindowsIdentity 对象代表曾经使用过的用户   使用Windows身份验证进行身份验有了这些对象,   角色列表自动从Windows组中获取   Windows用户所属的。
  •      

  • GenericPrincipal 和    GenericIdentity 对象代表曾经使用过的用户   使用Forms身份验证或其他自定义进行身份验   认证机制。使用这些对象,角色列表是   通过自定义方式获得,通常来自数据库。
  •      

  • FormsIdentity 和    PassportIdentity 对象代表拥有的用户   已通过Forms和Passport身份验证进行身份验证   分别。

     

下表说明了一系列IIS身份验证   设置,从每个设备获得的结果标识   保持 IPrincipal 和/或的变量    IIdentity 对象。以下缩写是   用于表中:

     

  • HttpContext =    HttpContext.Current.User ,返回一个   包含安全信息的 IPrincipal 对象   对于当前的Web请求。这是经过身份验证的Web   客户端。
  •      

  • WindowsIdentity =    WindowsIdentity.GetCurrent(),返回   当前正在执行的Win32的安全上下文的标识   线程。
  •      

  • 主题 =    Thread.CurrentPrincipal ,返回主体   当前正在执行的.NET线程,它位于Win32之上   线程。

        注意在Windows上运行IIS 6.0   Server 2003,身份Matrix工作,但Machine \ ASPNET除外   身份被NT Authority \ Network Service替换。

enter image description here

相关问题