Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

asp.net web api - WebApi with OWIN SelfHost and Windows Authentication

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...