11

I have a console application SERVER that hosts WebApi controllers using OWIN self-hosting, and runs under a custom account named "ServiceTest1".

In the same machine I have another console application CLIENT that runs under the account "ServiceTest2", and I want to capture in SERVER that "ServiceTest2" invoked a controller action. However:

  • WindowsIdentity.GetCurrent() is always "ServiceTest1".
  • Thread.CurrentPrincipal is an unauthenticated GenericIdentity.
  • RequestContext.Principal is null.
  • User is null.

What do I need to make this WebApi OWIN self-hosted to grab the Windows identity of the caller?

vtortola
  • 34,709
  • 29
  • 161
  • 263

1 Answers1

26

Your question is a little unclear on exactly how you've implemented the Windows authentication.

Enable Windows authentication:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        HttpListener listener = (HttpListener)app.Properties["System.Net.HttpListener"];
        listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;

        // ...
    }
}

Get the user in an OWIN middleware:

public async Task Invoke(IDictionary<string, object> env)
{
    OwinContext context = new OwinContext(env);
    WindowsPrincipal user = context.Request.User as WindowsPrincipal;

    //...
}

Get the user in a Web API Controller:

// In a web api controller function
WindowsPrincipal user = RequestContext.Principal as WindowsPrincipal;
Zephyr
  • 791
  • 5
  • 9
  • What is that `env` parameter? I have normal WebApi controllers that inherit from `ApiController`. – vtortola Aug 18 '15 at 21:56
  • Ah, I had read your question as wanting an OWIN method of grabbing the identity. I've edited my response with a Web API version as well. – Zephyr Aug 18 '15 at 22:35
  • `RequestContext.Principal` is null, any idea why? – vtortola Aug 19 '15 at 06:32
  • It is running with Windows authentication right? When you access the api from ServiceTest2, it has to log in using Windows credentials? Other than that, I'm not sure. My server running on Owin self host with Windows Auth seems to be able to access the request principal. – Zephyr Aug 19 '15 at 16:35
  • That is the question, how to set up Windows authentication in a WebAPI self-hosted with OWIN. How did you configure Windows Authentication? – vtortola Aug 19 '15 at 16:42
  • Ah, didn't realize you didn't have Windows auth already. Added some code for including that in OWIN startup. – Zephyr Aug 19 '15 at 20:58
  • When i want to get (System.Net.HttpListener)app.Properties["System.Net.HttpListener"] , it saying The given key was not present in the dictionary – Muhammad Saifullah Jan 05 '19 at 11:21