如何将ASP.NET身份验证传递给WCF服务
我有一个基本身份验证的WCF服务,它需要用户名和密码。我在一个胖客户端使用这项服务,用户名和密码存储在应用程序中,因此可以很容易地传递。如何将ASP.NET身份验证传递给WCF服务
我现在想在ASP.NET应用程序中使用此服务。我启用了安全性,并且工作正常。我想知道将这些凭据发送到我的Web服务的最佳方式。用户名我可以轻松使用this.User.Identity.Name,但密码更难。当然,我可以将它存储在一个加密的会话变量中,但这是正确的解决方案吗?代码段下方与目前硬编码密码所示: -
MyServiceClient client = new MyServiceClient();
client.ClientCredentials.UserName.UserName = this.User.Identity.Name;
client.ClientCredentials.UserName.Password = "Password";
BTW:这是我经过多年在这里寻找答案的第一个问题,所以请去容易对我:-)
启用身份验证服务 如果您还没有ASP.NET Web应用程序,请创建一个。 添加一个服务文件(.SVC)到包含以下指令引用AuthenticationService类,如下面的示例网站: VB
<%@ ServiceHost
Language="VB"
Service="System.Web.ApplicationServices.AuthenticationService"
Factory="System.Web.ApplicationServices.ApplicationServicesHostFactory" %>
C#
<%@ ServiceHost
Language="C#"
Service="System.Web.ApplicationServices.AuthenticationService"
Factory="System.Web.ApplicationServices.ApplicationServicesHostFactory" %>
请在Web.config以下配置设置文件来配置服务并要求SSL: 在authenticationService元素中启用身份验证服务。 定义服务元素中的端点合同和behavior元素中的服务行为。将bindingNamespace属性包含在端点合同中,如以下示例所示,以防止某些代理生成工具发生异常。有关WCF端点的更多信息,请参阅Windows Communication Foundation端点。 为了兼容ASP.NET,请配置serviceHostingEnvironment元素。有关托管WCF服务的更多信息,请参阅WCF服务和ASP.NET。 在需要SSL的绑定元素中创建一个绑定。有关WCF中传输安全性的更多信息,请参阅传输安全性。 以下示例显示了来自Web.config文件的system.serviceModel元素,该文件显示了上一列表中描述的配置设置。
<system.web.extensions>
<scripting>
<webServices>
<authenticationService enabled="true"
requireSSL = "true"/>
</webServices>
</scripting>
</system.web.extensions>
<system.serviceModel>
<services>
<service name="System.Web.ApplicationServices.AuthenticationService"
behaviorConfiguration="AuthenticationServiceTypeBehaviors">
<endpoint contract=
"System.Web.ApplicationServices.AuthenticationService"
binding="basicHttpBinding"
bindingConfiguration="userHttps"
bindingNamespace="http://asp.net/ApplicationServices/v200"/>
</service>
</services>
<bindings>
<basicHttpBinding>
<binding name="userHttps">
<security mode="Transport" />
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="AuthenticationServiceTypeBehaviors">
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment
aspNetCompatibilityEnabled="true"/>
</system.serviceModel>
To configure forms authentication
In the Web.config file, configure the Web application to use forms authentication.
The following example shows the authentication element in a Web.config file that is configured to use forms authentication.
<authentication mode="Forms">
<forms cookieless="UseCookies" />
</authentication>
验证服务需要cookie。因此,在认证元素中,将cookieless属性设置为“UseCookies”。有关更多信息,请参阅ASP.NET Forms身份验证概述。 安全 如果您正在传递身份验证凭据等敏感用户数据,请始终通过安全套接字层(SSL,使用HTTPS协议)访问身份验证服务。有关如何设置SSL的信息,请参阅配置安全套接字层(IIS 6.0操作指南)。