One of the features i really like in .NET 2.0 is that you get Kerberos support. NegotiateStream is an implementation of AuthenticatedStream (as SslStream is), so the source code is very similar to my last post.
Notice that you can access the client identity with the RemoteIdentity property. This is a WindowsIdentitiy object that you can use construct a WindowsPrincipal to call IsInRole on and you can set Thread.CurrentPrincipal to use the .NET role based security infrastructure. nice!
The Server
static void Main(string[] args)
{
TcpListener listener = new TcpListener(4242);
listener.Start();
Console.WriteLine(“Waiting for incoming connection…”);
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine(“Authenticating…”);
NegotiateStream kerb = new NegotiateStream(client.GetStream());
kerb.AuthenticateAsServer(CredentialCache.DefaultNetworkCredentials,
ProtectionLevel.EncryptAndSign,
TokenImpersonationLevel.Impersonation);
Console.WriteLine(“Client Identity: {0}”, kerb.RemoteIdentity.Name);
WindowsPrincipal principal = new WindowsPrincipal((WindowsIdentity)kerb.RemoteIdentity);
Console.WriteLine(“Is Admin? : {0}”, principal.IsInRole(WindowsBuiltInRole.Administrator));
Thread.CurrentPrincipal = principal;
DoSomethingOnlyDevelopersCanDo();
}
[PrincipalPermission(SecurityAction.Demand, Role=@”LEASTPRIVILEGEDevelopers”)]
static void DoSomethingOnlyDevelopersCanDo()
{
Console.WriteLine(“Developers only”);
}
The Client
static void Main(string[] args)
{
TcpClient client = new TcpClient();
client.Connect(“localhost”, 4242);
NegotiateStream kerb = new NegotiateStream(client.GetStream());
kerb.AuthenticateAsClient(CredentialCache.DefaultNetworkCredentials, “dbaier/leastprivilege”,
ProtectionLevel.EncryptAndSign,
System.Security.Principal.TokenImpersonationLevel.Impersonation);
StreamWriter writer = new StreamWriter(kerb);
writer.WriteLine(“Hello Kerberized Server”);
}