【发布时间】:2016-04-25 11:13:38
【问题描述】:
我有以下情况:
WPF client application -> WCF Service -> WebApi Service
我希望能够在 WebApi 服务中验证客户端应用程序的用户。我不需要完全的模拟/授权——我只需要客户的登录 ID,因为我正在使用第三方授权系统的用户 ID。 WCF Service 和 Web Api Service 在同一台服务器上。
我正在尝试的当前方法是模拟 WindowsIdentity,如下所示。
1.使用 Owin 自托管的 WebApi 服务
WebApp.Start(options,
builder =>
{
// Authenticate POST requests, but not GET requests
// Adapted from: http://stackoverflow.com/questions/17457382/windows-authentication-with-signalr-and-owin-self-hosting
var listener = (HttpListener)builder.Properties[typeof(HttpListener).FullName];
listener.AuthenticationSchemes =
AuthenticationSchemes.Negotiate | AuthenticationSchemes.Anonymous;
listener.AuthenticationSchemeSelectorDelegate =
request => (request.HttpMethod == HttpMethod.Get.Method)
? AuthenticationSchemes.Anonymous
: AuthenticationSchemes.Negotiate;
// etc
});
2。 WCF 服务
在<system.web>:<authentication mode="Windows" />
在<bindings>:
<binding name="BasicHttpEndpointBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" />
</security>
</binding>
在我要模拟的特定功能的代码中:
WindowsIdentity callerIdentity = ServiceSecurityContext.Current.WindowsIdentity;
using (callerIdentity.Impersonate())
{
var request = ...;
request.ImpersonationLevel = TokenImpersonationLevel.Impersonation;
request.UseDefaultCredentials = true;
// Use request to call Web Api
}
3.在客户端:
<endpointBehaviors>
<behavior name="ImpersonationBehavior">
<clientCredentials>
<windows allowedImpersonationLevel="Impersonation" />
</clientCredentials>
</behavior>
</endpointBehaviors>
在我的本地 PC 上进行此设置后,我看到 WCF 服务尝试连接到 WebApi 服务时出现错误:
{"An attempt was made to access a socket in a way forbidden by its access permissions 127.0.0.1:9102"}
(请注意,使用 WindowsIdentity callerIdentity = WindowsIdentity.GetCurrent(); 而不是 WindowsIdentity callerIdentity = ServiceSecurityContext.Current.WindowsIdentity; 可以正常工作 - 尽管显然这是使用 WCF 用户而不是客户端应用程序用户)
我的问题 - 这是在 Web Api 服务中确定用户名的最明智的方法吗?甚至有可能这样吗?如果是这样,知道如何调试“禁止”错误并使此设置正常工作吗?
【问题讨论】:
标签: c# asp.net-web-api owin windows-authentication wcf-security