WCF安全參數(shù)正確設(shè)置方式解讀
WCF開發(fā)工具的推出,對(duì)開發(fā)人員來說帶來了非常不一般的使用體驗(yàn)。那么今天在這篇文章中,我們將會(huì)為大家詳細(xì)介紹一下有關(guān)WCF安全參數(shù)的正確設(shè)置方法,希望能夠?qū)τ中枰呐笥延兴鶐椭?/p>
1. 安全方式
通過設(shè)置 Binding 的屬性 Security 來實(shí)現(xiàn)WCF安全參數(shù)的設(shè)置。
- NetTcpBinding binding = new NetTcpBinding();
- binding.Security.Mode = SecurityMode.Transport;
- binding.Security.Transport.ProtectionLevel =
System.Net.Security.ProtectionLevel.EncryptAndSign;
2. 消息保護(hù)
通過 ServiceContractAttribute 和 OperationContractAttribute 特性的 ProtectionLevel 參數(shù)我們可以設(shè)置不同的消息保護(hù)級(jí)別。
- [ServiceContract(ProtectionLevelProtectionLevel =
ProtectionLevel.EncryptAndSign)]- interface IMyContract
- {
- ...
- }
3. 身份驗(yàn)證
不同的部署環(huán)境,會(huì)采取不同的選擇來進(jìn)行WCF安全參數(shù)的設(shè)置。在 Intranet 環(huán)境下,我們可能選擇 Windows 集成驗(yàn)證方式,而在 Internet 環(huán)境下通常的方案是采取 X.509 數(shù)字證書,當(dāng)然最最通用最最常見依然是用戶名/密碼。
以 Windows 集成驗(yàn)證為例,客戶端可以通過 ClientBase.ClientCredentials 屬性向服務(wù)器端發(fā)送與其相匹配的身份驗(yàn)證信息。缺省情況下,客戶端使用當(dāng)前 Windows 登錄賬戶作為身份驗(yàn)證信息,我們也可以顯式設(shè)置不同的身份信息。
代理方式:
- NetworkCredential credentials = new NetworkCredential( );
- credentials.Domain = "MyDomain";
- credentials.UserName = "MyUsername";
- credentials.Password = "MyPassword";
- using (MyContractClient client = new MyContractClient())
- {
- client.ClientCredentials.Windows.ClientCredential = credentials;
- client.MyMethod( );
- }
工廠方式:
- ChannelFactory<IMyContract> factory = new ChannelFactory<IMyContract>("");
- factory.Credentials.Windows.ClientCredential = new NetworkCredential(...);
- IMyContract client = factory.CreateChannel( );
- using(client as IDisposable)
- {
- client.MyMethod( );
- }
在服務(wù)中,我們可以用 ServiceSecurityContext.Current (或者 OperationContext.Current.ServiceSecurityContext) 來獲取相關(guān)身份信息。
- Console.WriteLine(ServiceSecurityContext.Current.
WindowsIdentity.AuthenticationType);- Console.WriteLine(ServiceSecurityContext.Current.
WindowsIdentity.Name);
以上就是我們介紹的WCF安全參數(shù)的設(shè)置方法。
【編輯推薦】