Friday, 19 October 2012

Custom Credentials in TCP Remoting using C#




Having been looking at custom credentials in TCP remoting there was an issue when switching between custom credentials and using the default credentials of the current process (this is the default behaviour).

The following C# code sample shows how to pass the custom credentials to the remoting object by modifying the sink properties using the following command.
IDictionary Properties = ChannelServices.GetChannelSinkProperties(Current);
 
The issue that didn't seem clear was how do you switch back to using the default credentials...
 
After trying a few different methods it seems that you need to modify the IDictionary and rather than removing the credentials from the collection set them to null as seen in the example below.
 
 
/// <summary>
/// Connects to the service remote using the specified settings
/// </summary>
/// <param name="MachineName">The name of the remote machine to connect to</param>
/// <param name="Credentials">The credentials to use for the connection</param>
/// <param name="Port">The TCP port number</param>
/// <returns>A connected service remote object</returns>
public static IServiceRemote Connect(String MachineName, ConnectionCredentials Credentials, int Port)
{
     if (IsConnected) Disconnect();
     TCPClient = new TcpClientChannel();
     ChannelServices.RegisterChannel(TCPClient, true);
     String ObjectURI = String.Format("tcp://{0}:{1}/RemoteObject.rem", MachineName, Port);
     Current = (IServiceRemote)Activator.GetObject(typeof(IServiceRemote), ObjectURI);
     IDictionary Properties = ChannelServices.GetChannelSinkProperties(Current);
     if (Credentials.UseDefaultCredentials == false)
     {
          Properties["domain"] = Credentials.Domain;
          Properties["username"] = Credentials.UserName;
          Properties["password"] = Credentials.Password;
     }
     else
     {
          Properties["domain"] = null;
          Properties["username"] = null;
          Properties["password"] = null;
     }
     return Current;
}

 

No comments:

Post a Comment