Saturday, February 27, 2010

How to determine the server certificate given an https wcf proxy?

One day when you are using https transports in WCF you might try to figure out what certificate the server is using. That is going to be the day you're glad you found my blog.

 
namespace WebClient
{
using System;
using System.IdentityModel.Tokens;
using System.ServiceModel;
using System.ServiceModel.Channels;

///
/// Interface implemented by a random https bound web service I found on the web.
///

[ServiceContract (Namespace="http://arcweb.esri.com/v2")]
interface IVersion
{
[OperationContract]
string getVersion();
}

class Program
{
static void Main(string[] args)
{
var httpsBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
var endpointAddress = new EndpointAddress("https://arcweb.esri.com/services/v2/AccountInfo");
var serviceClient = new ChannelFactory<IVersion>(httpsBinding, endpointAddress).CreateChannel();

// Instantiating an OperationContextScope populates the OperationContext.Current property
using (OperationContextScope scope = new OperationContextScope(serviceClient as IContextChannel))
{
serviceClient.getVersion();
// Certificate not available until after an API call.
var myCertificate = (OperationContext.Current.IncomingMessageProperties.Security.TransportToken.SecurityToken as X509SecurityToken).Certificate;
Console.WriteLine(myCertificate);
}
}
}
}


I expect most folks will skip this post, but if you end up needing this tip leave a comment with what you’re up to -  I’m curious!

0 comments:

Post a Comment