我编写了一个与 WCF 服务 (BasicHttpBinding) 通信的 Silverlight 2 应用程序。托管 Silverlight 内容的站点使用 ASP.NET 成员资格提供程序进行保护。我可以使用 WCF 服务中的 HttpContext.Current.User.Identity.Name 访问当前用户,并且我已打开 AspNetCompatibilityRequirementsMode。
我现在想使用完全相同的 Web 服务编写一个 Windows 应用程序。为了处理身份验证,我启用了认证服务,并且可以调用“登录”来验证我的用户...好吧,一切都好...但是我到底如何在我的其他服务客户端上设置验证 cookie?
两种服务都托管在同一域上
- MyDataService.svc
- AuthenticationService.svc
我不想为 Windows 客户端创建新服务,或使用其他绑定...
客户端应用程序服务是另一种选择,但所有示例都仅限于展示如何获取用户、角色及其个人资料...但是一旦我们使用客户端应用程序服务进行身份验证,就应该有一种方法来获取该身份验证 cookie当回调到同一服务器时附加到我的服务客户端。
根据同事的意见,解决方案是添加一个 wsHttpBinding 端点,但我希望我可以解决这个问题......
我终于找到了一种方法来完成这项工作。为了进行身份验证,我使用“WCF 身份验证服务“。当对服务进行身份验证时,将尝试设置一个身份验证 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();
}
正如您所看到的,我有两个服务客户端,一个用于身份验证服务,另一个用于我实际要使用的服务。第一个块将调用 Login 方法,并从响应中获取身份验证 cookie。第二个块将在调用“GetDives”服务方法之前将标头添加到请求中。
我对这段代码根本不满意,我认为更好的选择可能是使用“Web 引用”而不是“服务引用”并使用 .NET 2.0 堆栈。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)