我编写了一个与 WCF 服务 (BasicHttpBinding) 通信的 Silverlight 2 应用程序。托管 Silverlight 内容的站点使用 ASP.NET 成员资格提供程序进行保护。我可以使用 WCF 服务中的 HttpContext.Current.User.Identity.Name 访问当前用户,并且我已经打开了 AspNetCompatibilityRequirementsMode。
我现在想使用完全相同的 Web 服务编写一个 Windows 应用程序。为了处理身份验证,我启用了 Authentication service ,并且可以调用“登录”来验证我的用户......好吧,一切都很好......但是我怎么能在我的其他服务客户端上设置那个身份验证cookie?!
两种服务都托管在同一个域上
我不想为 Windows 客户端创建新服务,或者使用其他绑定(bind)...
客户端应用程序服务是另一种选择,但所有示例都仅限于展示如何获取用户、角色和他的个人资料......但是一旦我们使用客户端应用程序服务进行身份验证,就应该有一种方法来获取该身份验证 cookie回调到同一服务器时附加到我的服务客户端。
根据同事的意见,解决方案是添加一个 wsHttpBinding 端点,但我希望我能解决这个问题......
最佳答案
我终于找到了一种方法来完成这项工作。对于身份验证,我使用“WCF Authentication Service”。验证服务时会尝试设置验证 cookie。我需要从响应中获取此 cookie,并将其添加到对同一台机器上的其他 Web 服务发出的任何其他请求中。执行此操作的代码如下所示:
var authService = new AuthService.AuthenticationServiceClient();
var diveService = new DiveLogService.DiveLogServiceClient();
string cookieHeader = "";
using (OperationContextScope scope = new OperationContextScope(authService.InnerChannel))
{
HttpRequestMessageProperty requestProperty = new HttpRequestMessageProperty();
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestProperty;
bool isGood = authService.Login("jonas", "jonas", string.Empty, true);
MessageProperties properties = OperationContext.Current.IncomingMessageProperties;
HttpResponseMessageProperty responseProperty = (HttpResponseMessageProperty)properties[HttpResponseMessageProperty.Name];
cookieHeader = responseProperty.Headers[HttpResponseHeader.SetCookie];
}
using (OperationContextScope scope = new OperationContextScope(diveService.InnerChannel))
{
HttpRequestMessageProperty httpRequest = new HttpRequestMessageProperty();
OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpRequest);
httpRequest.Headers.Add(HttpRequestHeader.Cookie, cookieHeader);
var res = diveService.GetDives();
}
如您所见,我有两个服务客户端,一个用于身份验证服务,一个用于我实际要使用的服务。第一个 block 将调用 Login 方法,并从响应中获取身份验证 cookie。第二个 block 将在调用“GetDives”服务方法之前将 header 添加到请求中。
我对这段代码一点也不满意,我认为更好的选择可能是使用“Web Reference”而不是“Service Reference”并使用 .NET 2.0 堆栈。
关于.net - WCF、ASP.NET 成员资格提供程序和身份验证服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56112/