2010-10-13 22 views
6

Tôi muốn có thể sử dụng xác thực tên người dùng/mật khẩu với nettcpbinding, là có thể? (UserNamePasswordValidator hoặc một cái gì đó như thế), không có cửa sổ xác thực.Làm cách nào để định cấu hình xác thực tên người dùng/mật khẩu cho WCF netTcpBinding?

Tôi định cấu hình mọi thứ bằng mã, vì vậy, vui lòng chỉ sử dụng mã chứ không phải ứng dụng.config trong bất kỳ ví dụ nào.

Trả lời

14

Đây là những gì tôi đã đưa ra, tôi không có ý tưởng nếu một số mã không cần thiết:

máy chủ dịch vụ:

 ServiceHost host = new ServiceHost(concreteType); 
     var binding = new NetTcpBinding(SecurityMode.TransportWithMessageCredential, true); 
     binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName; 
     host.AddServiceEndpoint(serviceType, binding, "net.tcp://someaddress:9000/" + name); 
     host.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new CustomUserNameValidator(); 
     host.Credentials.ServiceCertificate.Certificate = new X509Certificate2("mycertificate.p12", "password"); 
     host.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = 
      UserNamePasswordValidationMode.Custom; 

Và phía khách hàng:

 var binding = new NetTcpBinding(SecurityMode.TransportWithMessageCredential, true); 
     binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName; 

     var factory = new ChannelFactory<ISwitchService>(binding, 
                 new EndpointAddress(
                  new Uri("net.tcp://someaddress:9000/switch"))); 
     factory.Credentials.UserName.UserName = "myUserName"; 
     factory.Credentials.UserName.Password = "myPassword"; 
+0

Cảm ơn cho một câu trả lời rõ ràng như vậy. Giúp tôi khá nhiều. – Kelly