Certificate-based web services security之感性认识
时间:2010-08-25 来源:zzfff
我对Web Services Security理解也很肤浅,本文不严谨。
下面的.net console application,添加System.ServiceModel.dll程序集引用即可,不需要配置文件。
/* ===SET CERT=== makecert.exe -a sha1 -n CN=MyService.com -sr LocalMachine -ss My -sky exchange -sk MyService certmgr.exe -add -c -n MyService.com -s -r localMachine My -s -r localMachine TrustedPeople makecert.exe -a sha1 -n CN=MyClient.com -sr LocalMachine -ss My -sky exchange -sk MyClient certmgr.exe -add -c -n MyClient.com -s -r localMachine My -s -r localMachine TrustedPeople ===CLEAN CERT=== certmgr.exe -del -c -n MyService.com -r localmachine -s My certmgr.exe -del -c -n MyService.com -r localmachine -s TrustedPeople certmgr.exe -del -c -n MyClient.com -r localmachine -s My certmgr.exe -del -c -n MyClient.com -r localmachine -s TrustedPeople */ using System; using System.ServiceModel; using System.ServiceModel.Description; using System.ServiceModel.Security; using System.Security.Cryptography.X509Certificates; [ServiceContract] interface ISomeContract { [OperationContract] string SomeOperation(int i); } class SomeService : ISomeContract { string ISomeContract.SomeOperation(int i) { Console.WriteLine("SomeOperation:" + i); return i.ToString("X"); } static void Main() { using (ServiceHost sh = new ServiceHost(typeof(SomeService), new Uri("http://localhost:8000"))) { WS2007HttpBinding b = new WS2007HttpBinding(SecurityMode.Message); b.Security.Message.ClientCredentialType = MessageCredentialType.Certificate; b.Security.Message.NegotiateServiceCredential = false; b.Security.Message.EstablishSecurityContext = false; sh.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, "MyService.com"); sh.Credentials.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerOrChainTrust; sh.AddServiceEndpoint(typeof(ISomeContract), b, ""); ServiceMetadataBehavior smb = new ServiceMetadataBehavior() { HttpGetEnabled = true }; sh.Description.Behaviors.Add(smb); sh.Open(); Console.Write("Service started, press any key to start client..."); Console.ReadLine(); ChannelFactory<ISomeContract> cf = new ChannelFactory<ISomeContract>(b, new EndpointAddress(new Uri("http://localhost:8000"), EndpointIdentity.CreateDnsIdentity("MyService.com"))); cf.Credentials.ClientCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, "MyClient.com"); cf.Credentials.ServiceCertificate.SetDefaultCertificate(StoreLocation.LocalMachine, StoreName.TrustedPeople, X509FindType.FindBySubjectName, "MyService.com"); //cf.Endpoint.Behaviors.Add(new ClientViaBehavior(new Uri("http://localhost:8001"))); ISomeContract sc = cf.CreateChannel(); using (sc as IDisposable) { Console.WriteLine("Client:" + sc.SomeOperation(15)); } Console.Write("Press any key to end..."); Console.ReadLine(); } } }
相关阅读 更多 +