NegotiateStream Sample

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! (8.01 KB)

The Server

static void Main(string[] args)
    TcpListener listener = new TcpListener(4242);

    Console.WriteLine(“Waiting for incoming connection…”);
    TcpClient client = listener.AcceptTcpClient();

    NegotiateStream kerb = new NegotiateStream(client.GetStream());


    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;

[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”,

    StreamWriter writer = new StreamWriter(kerb);
    writer.WriteLine(“Hello Kerberized Server”);


This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s