http://dotnetdlr.comImplement windows authentication andsecurity in WCF ServiceThis is continuation with previous post on ...
http://dotnetdlr.com       //privacy, and authenticity.       tcpbinding.Security.Transport.ProtectionLevel =       System...
http://dotnetdlr.com tcpbinding.Security.Transport.ProtectionLevel =               System.Net.Security.ProtectionLevel.Enc...
http://dotnetdlr.comClient Application    static void Main(string[] args)     {     try         {           Console.WriteL...
http://dotnetdlr.com         public ServiceClient(System.ServiceModel.Channels.Binding binding,                           ...
http://dotnetdlr.comNow If I run client application with changed credentials, if credentials are of valid windows user,ser...
Upcoming SlideShare
Loading in...5
×

Implement Windows Authentication And Security In Wcf Service

3,119

Published on

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
3,119
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
34
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Implement Windows Authentication And Security In Wcf Service

  1. 1. http://dotnetdlr.comImplement windows authentication andsecurity in WCF ServiceThis is continuation with previous post on “Security in WCF -I”.Here I’ll explain how we can implement windows authentication with transport level security inintranet environment.Windows authenticationIn intranet environment, client and service are .Net application.Windows authentication is mostsuitable authentication type in intranet where client credentials stored in windows accounts &groups. Intranet environment address a wide range of business applications. Developers havemore controlled in this environment.For Intranet, you can use netTcpBinding,NetNamedPipeBinding and NetMsmqBinding forsecure and fast communication.Windows credential is default credential type and transport security is default security mode forthese bindings.Protection LevelYou can set Transport Security protection level through WCF:  None: WCF doesn’t protect message transfer from client to service.  Signed: WCF ensures that message have come only from authenticated caller. WCF checks validity of message by checking Checksum at service side. It provides authenticity of message.  Encrypted & Signed: Message is signed as well as encrypted. It provides integrity, privacy and authenticity of message.Configuration in WCF Service for Windows Authentication Service is hosted on netTcpBinding with credential type windows and protection level as EncryptedAndSigned. var tcpbinding = new NetTcpBinding(SecurityMode.Transport); //Client credential will be used of windows user tcpbinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows; // When configured for EncryptAndSign protection level, WCF both signs the message and encrypts //its content. The Encrypted and Signed protection level provides integrity, 1
  2. 2. http://dotnetdlr.com //privacy, and authenticity. tcpbinding.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign;Client credential type can be set by TcpClientCredentialType enum.public enum TcpClientCredentialType{None,Windows,Certificate}Protection level can be set by ProtectionLevel enum. // Summary: // Indicates the security services requested for an authenticatedstream. public enum ProtectionLevel { // Summary: // Authentication only. None = 0, // // Summary: // Sign data to help ensure the integrity of transmitted data. Sign = 1, // // Summary: // Encrypt and sign data to help ensure the confidentiality andintegrity of // transmitted data. EncryptAndSign = 2, }WCF Service CodeService Hostclass Program {static void Main(string[] args){Uri baseAddress = new Uri("http://localhost:8045/MarketService");using (var productHost = new ServiceHost(typeof(MarketDataProvider))) { var tcpbinding = new NetTcpBinding(SecurityMode.Transport); //Client credential will be used of windows user tcpbinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows; // When configured for EncryptAndSign protection level, WCF both signs themessage and encrypts //its content. The Encrypted and Signed protection level provides integrity, //privacy, and authenticity. 2
  3. 3. http://dotnetdlr.com tcpbinding.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign; ServiceEndpoint productEndpoint = productHost. AddServiceEndpoint(typeof(IMarketDataProvider), tcpbinding, "net.tcp://localhost:8000/MarketService"); ServiceEndpoint producthttpEndpoint = productHost.AddServiceEndpoint( typeof(IMarketDataProvider), new BasicHttpBinding(), "http://localhost:8045/MarketService"); productHost.Open(); Console.WriteLine("The Market service is running and is listening on:"); Console.WriteLine("{0} ({1})", productEndpoint.Address.ToString(), productEndpoint.Binding.Name); Console.WriteLine("{0} ({1})", producthttpEndpoint.Address.ToString(), producthttpEndpoint.Binding.Name); Console.WriteLine("nPress any key to stop the service."); Console.ReadKey(); } } }Alternatively, you can configure the binding using a config file:<bindings><netTcpBinding><binding name = "TCPWindowsSecurity"><security mode = "Transport"><transportclientCredentialType = "Windows"protectionLevel = "EncryptAndSign"/></security></binding></netTcpBinding></bindings>Run WCF Service 3
  4. 4. http://dotnetdlr.comClient Application static void Main(string[] args) { try { Console.WriteLine("Connecting to Service.."); var proxy = new ServiceClient(new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:8000/MarketService")); Console.WriteLine("MSFT Price:{0}", proxy.GetMarketPrice("MSFT.NSE")); Console.WriteLine("Getting price for Google"); double price = proxy.GetMarketPrice("GOOG.NASDAQ"); } catch (FaultException ex) { Console.WriteLine("Service Error:" + ex.Detail.ValidationError); } catch (Exception ex) { Console.WriteLine("Service Error:" + ex.Message); } Console.ReadLine();}ServiceClient is custom class which inherits ClientBase<T> class in System.ServiceModelnamespace to create channels and communication with service on endpoints.public class ServiceClient : ClientBase, IMarketDataProvider { public ServiceClient() { } public ServiceClient(string endpointConfigurationName) : base(endpointConfigurationName) { } public ServiceClient(string endpointConfigurationName, stringremoteAddress) : base(endpointConfigurationName, remoteAddress) { } public ServiceClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : base(endpointConfigurationName, remoteAddress) { } 4
  5. 5. http://dotnetdlr.com public ServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : base(binding, remoteAddress) {} /// /// IMarketDataProvider method /// /// /// public double GetMarketPrice(string symbol) { return base.Channel.GetMarketPrice(symbol); } }Verify User credentials in ServiceYou can see caller information in WCF service by ServiceSecurityContext class. Every operationon a secured WCF service has a security call context. The security call context is represented bythe class ServiceSecurityContext.The main use for the security call context is for custom securitymechanisms, as well as analysis and auditing.ServiceSecurityContext.Current in Quickwatch window.Send Alternate Windows credentials to ServiceWCF also give option to send alternate windows credential from client. By default it send loggedin user credential. You can send alternate credential like belowproxy.ClientCredentials.Windows.ClientCredential.Domain = "mydomain";proxy.ClientCredentials.Windows.ClientCredential.UserName = "ABC";proxy.ClientCredentials.Windows.ClientCredential.Password = "pwd"; 5
  6. 6. http://dotnetdlr.comNow If I run client application with changed credentials, if credentials are of valid windows user,service will authenticate caller else it will reject caller request. In my case I deliberately giveswrong credential to produce reject exception.Service sends “System.Security.Authentication.InvalidCredentialException with message "Theserver has rejected the client credentials.”I hope you understood windows authentication concept here. If you have any question please feelfree to send me comments. 6

×