title: WCF Authentication with custom ClientCredentials: What is the clientCredentialType to use?
body: <p>I had to ditch the basic WCF UserName/Pwd security and implement my own custom client credentials to hold some more info beyond what is provided by default.</p>
  
  <p>I worked through<a href="http://msdn.microsoft.com/en-us/library/ms730868.aspx" rel="noreferrer">this MSDN article</a>, but I'm missing something because it doesn't work.</p>
  
  <p>First, I have some custom ClientCredentials that provide a custom ClientCredentialsSecurityTokenManager:</p>
  
  <pre><code>public class CentralAuthCredentials : ClientCredentials
  {
      public override System.IdentityModel.Selectors.SecurityTokenManager CreateSecurityTokenManager()
      {
          return new CentralAuthTokenManager(this);
      }
  }
  
  public class CentralAuthTokenManager : ClientCredentialsSecurityTokenManager
  {
      private CentralAuthCredentials credentials;
  
      public CentralAuthTokenManager(CentralAuthCredentials creds) : base(creds)
      {
          this.credentials = creds;
      }
  
      public override SecurityTokenProvider CreateSecurityTokenProvider(SecurityTokenRequirement tokenRequirement)
      {
          if (this.IsIssuedSecurityTokenRequirement(tokenRequirement) || tokenRequirement.TokenType == CentralAuthToken.TOKEN_TYPE)
              return new CentralAuthTokenProvider(credentials.UserId, credentials.UserPassword, credentials.ImpersonateId, credentials.LoginType);
          else
              return base.CreateSecurityTokenProvider(tokenRequirement);
      }
  
      public override SecurityTokenAuthenticator CreateSecurityTokenAuthenticator(SecurityTokenRequirement tokenRequirement, out SecurityTokenResolver outOfBandTokenResolver)
      {
          outOfBandTokenResolver = null;
          if (this.IsIssuedSecurityTokenRequirement(tokenRequirement) || tokenRequirement.TokenType == CentralAuthToken.TOKEN_TYPE)
              return new CentralAuthTokenAuthenticator();
          else
              return base.CreateSecurityTokenAuthenticator(tokenRequirement, out outOfBandTokenResolver);
      }
  
      public override SecurityTokenSerializer CreateSecurityTokenSerializer(SecurityTokenVersion version)
      {
          return new CentralAuthTokenSerializer();
      }
  }
  </code></pre>
  
  <p>Now when I run the app, my custom credentials and token manager do get created.
  However, in the method:</p>
  
  <pre><code>CreateSecurityTokenProvider(SecurityTokenRequirement tokenRequirement)
  {
      ...
  }
  </code></pre>
  
  <p>The tokenRequirement.TokenType comes across as something other than my custom token. That brings up my <strong>1st question</strong>: How the heck does WCF know what the token requirements are?</p>
  
  <p>Also, the method:</p>
  
  <pre><code>public override SecurityTokenSerializer CreateSecurityTokenSerializer(SecurityTokenVersion version)
  {
      return new CentralAuthTokenSerializer();
  }
  </code></pre>
  
  <p>Does get called once by the client, but none of the methods on the returned token serializer are ever called. This indicates to me that the custom token is never being sent across the wire. I assume this is because the call to CreateSecurityTokenProvider() never returned my custom token provider, since the SecurityTokenRequirement is never passed in indicating my custom token is needed.</p>
  
  <p>On the client side, I have:</p>
  
  <pre><code>public class CentralAuthorizationManagerClient : ClientBase&lt;ICentralAuthorizationManager&gt;, ICentralAuthorizationManager, IDisposable
  {
      public PFPrincipal GenerateToken()
      {
          if (!this.ChannelFactory.Endpoint.Behaviors.Contains(typeof(CentralAuthCredentials)))
              throw new ArgumentException("Must set CentralAuthCredentials before calling this method.");
          return base.Channel.GenerateToken();
      }
  
      public PFPrincipal GenerateToken(CentralAuthToken token)
      {
          this.ChannelFactory.Endpoint.Behaviors.Remove&lt;ClientCredentials&gt;();
          this.ChannelFactory.Endpoint.Behaviors.Add(new CentralAuthCredentials(token));
          return this.GenerateToken();
      }
  </code></pre>
  
  <p>These methods are basically supposed to remove the default credentials from the endpoint and attach a new instance of my custom CentralAuthCredentials. (I grabbed this Remove/Add combo from an MSDN article somewhere).</p>
  
  <p>In the configuration:</p>
  
  <pre><code>    &lt;behaviors&gt;
          &lt;endpointBehaviors&gt;
              &lt;behavior name="Server2ServerEndpointBehavior"&gt;
                  &lt;clientCredentials type="MyApp.Security.CentralAuthCredentials, MyApp"&gt;
                      &lt;clientCertificate findValue="localhost" x509FindType="FindBySubjectName" storeLocation="CurrentUser" storeName="My" /&gt;
                      &lt;serviceCertificate&gt;
                          &lt;authentication certificateValidationMode="None" revocationMode="NoCheck" /&gt;
                      &lt;/serviceCertificate&gt;
                  &lt;/clientCredentials&gt;
              &lt;/behavior&gt;
          &lt;/endpointBehaviors&gt;
      &lt;/behaviors&gt;
  
      &lt;bindings&gt;
          &lt;wsHttpBinding&gt;
              &lt;binding name="wsHttpServer2Server"&gt;
                  &lt;security mode="Message"&gt;
                      &lt;message clientCredentialType="UserName" /&gt;
                  &lt;/security&gt;
              &lt;/binding&gt;
          &lt;/wsHttpBinding&gt;
      &lt;/bindings&gt;
  </code></pre>
  
  <p>Note that the behavior's clientCredentials type is set to my custom client credentials. However, at the moment I still have the binding's clientCredentialType set to "UserName". This brings up my <strong>2nd question</strong>: What the heck should clientCredentialType="?" be set to if I'm using custom credentials? According to MSDN, the available values for <em>Message</em> security are: <em>None</em>, <em>Windows</em>, <em>UserName</em>, <em>Certificate</em>, and <em>IssuedToken</em>.</p>
  
  <p>Any ideas? Hopefully I'm just missing something simple?  There are like 6 more classes to the entire implementation, but I tried to only include the bits needed to understand the situation...</p>
  
  <hr>
  
  <p><strong>UPDATE #1:</strong></p>
  
  <p>I've been working on this all day, and thanks to a few sources, I realized that part of what I was missing was the very last step on <a href="http://msdn.microsoft.com/en-us/library/ms731872.aspx" rel="noreferrer">this page</a>, which is adding the TokenParameters to the binding, so that the binding knows what the token looks like. That is the answer to my original 1st question; "what the heck sets up the token requirements?" Answer: the TokenParameters assigned to the binding.</p>
  
  <p>So now I added the following extension which sets the TokenParameters on the binding:</p>
  
  <pre><code>public sealed class CentralAuthTokenBindingExtension : BindingElementExtensionElement
  {
      public CentralAuthTokenBindingExtension()
          : base()
      {
      }
  
      public override Type BindingElementType
      {
          get { return typeof(SymmetricSecurityBindingElement); }
      }
  
      protected override System.ServiceModel.Channels.BindingElement CreateBindingElement()
      {
          X509SecurityTokenParameters protectionParams = new X509SecurityTokenParameters();
          protectionParams.InclusionMode = SecurityTokenInclusionMode.Never;
  
          SymmetricSecurityBindingElement innerBindingElement = new SymmetricSecurityBindingElement();
          innerBindingElement.EndpointSupportingTokenParameters.SignedEncrypted.Add(new CentralAuthTokenParameters());
          //innerBindingElement.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;
          innerBindingElement.ProtectionTokenParameters = protectionParams;
  
          return innerBindingElement;
      }
  }
  
      &lt;extensions&gt;
          &lt;bindingElementExtensions&gt;
              &lt;add name="CentralAuthCreds" type="MyApp.Security.Configuration.CentralAuthTokenBindingExtension, MyApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" /&gt;
          &lt;/bindingElementExtensions&gt;
      &lt;/extensions&gt;
  
      &lt;bindings&gt;
          &lt;customBinding&gt;
              &lt;binding name="wsHttpServer2Server"&gt;
                  &lt;CentralAuthCreds /&gt;
                  &lt;binaryMessageEncoding /&gt;
                  &lt;httpTransport /&gt;
              &lt;/binding&gt;
          &lt;/customBinding&gt;
      &lt;/bindings&gt;
  </code></pre>
  
  <p>Well that gets me a step further. Now I get a new exception on the server: </p>
  
  <pre><code>"The security token manager cannot create a token authenticator for requirement ..."
  </code></pre>
  
  <p>It looks like WCF is using some default token manager to try to deal with my custom token, instead of my custom token handler (my custom token handler's constructor is never called).  I <em>think</em> this is happening because for the <em>client</em>, I have this config:</p>
  
  <pre><code>&lt;endpointBehaviors&gt;
      &lt;behavior name="Server2ServerEndpointBehavior"&gt;
          &lt;clientCredentials type="MyApp.Security.CentralAuthCredentials, MyApp"&gt;
  </code></pre>
  
  <p>But on the <em>server</em> I don't have any equivalent to let it know about the custom client credentials. So, <strong>new question</strong>: Where in the config for the server do I tell it what the custom ClientCredentials are?</p>
  
  <hr>
  
  <p><strong>Update #2:</strong></p>
  
  <p>Well, I finally figured out a bit more of the puzzle.  I had only implemented a ClientCredentials implementation, thinking that the client sends creds, and thats it. The client doesnt authenticate the service, so I don't need custom ServiceCredentials.  Well, I was wrong. The specified ServiceCredentials authenticates the token from the ClientCredentials, and vice-versa. So I just had to add a custom ServiceCredentials implementation that passed the same TokenSerializer and TokenAuthenticator classes.</p>
  
  <p>On to the next issue: WCF is now ignoring my x509 certs specified in config that were working fine with UserName auth.  I'm going to open a whole new question for this one!</p>