扩展Wcf call security service, 手动添加 Soap Security Head.

有次我们有个项目需要Call 一个 Java 的 web service, Soap包中需要一个 Security Head

  1. <soapenv:Header>
  2. <wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
  3. <wsse:UsernameToken xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" wsu:Id="UsernameToken-1" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
  4. <wsse:Username>username</wsse:Username>
  5. <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">password</wsse:Password>
  6. </wsse:UsernameToken>
  7. </wsse:Security>
  8. </soapenv:Header>

但是.net 默认的 Credentials 添加的 UserName 不符合这种格式

  1. orgClient.ClientCredentials.UserName.UserName = "userName";
  2. orgClient.ClientCredentials.UserName.Password = "password";

所以总是报错

System.Web.Services.Protocols.SoapHeaderException: An error was

discovered processing the <wsse: Security> header

 

没奈何,就只有用力气活,手动的把这段WSSE 的 head 添加到 Soap 包里面去了。

  1. orgClient.Endpoint.EndpointBehaviors.Add(new CustomEndpointBehavior());

下面是Behavior

  1. /// <summary>
  2.     /// Represents a run-time behavior extension for a client endpoint.
  3.     /// </summary>
  4.     public class CustomEndpointBehavior : IEndpointBehavior
  5.     {
  6.         /// <summary>
  7.         /// Implements a modification or extension of the client across an endpoint.
  8.         /// </summary>
  9.         /// <param name="endpoint">The endpoint that is to be customized.</param>
  10.         /// <param name="clientRuntime">The client runtime to be customized.</param>
  11.         public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
  12.         {
  13.             clientRuntime.ClientMessageInspectors.Add(new ClientMessageInspector());
  14.         }
  15.  
  16.         /// <summary>
  17.         /// Implement to pass data at runtime to bindings to support custom behavior.
  18.         /// </summary>
  19.         /// <param name="endpoint">The endpoint to modify.</param>
  20.         /// <param name="bindingParameters">The objects that binding elements require to support the behavior.</param>
  21.         public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
  22.         {
  23.             // Nothing special here
  24.         }
  25.  
  26.         /// <summary>
  27.         /// Implements a modification or extension of the service across an endpoint.
  28.         /// </summary>
  29.         /// <param name="endpoint">The endpoint that exposes the contract.</param>
  30.         /// <param name="endpointDispatcher">The endpoint dispatcher to be modified or extended.</param>
  31.         public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
  32.         {
  33.             // Nothing special here
  34.         }
  35.  
  36.         /// <summary>
  37.         /// Implement to confirm that the endpoint meets some intended criteria.
  38.         /// </summary>
  39.         /// <param name="endpoint">The endpoint to validate.</param>
  40.         public void Validate(ServiceEndpoint endpoint)
  41.         {
  42.             // Nothing special here
  43.         }
  44.     }

请注意13行红色部分的代码,相当于一层层的使用了Provider 的模式

  1. /// <summary>
  2.     /// Represents a message inspector object that can be added to the <c>MessageInspectors</c> collection to view or modify messages.
  3.     /// </summary>
  4.     public class ClientMessageInspector : IClientMessageInspector
  5.     {
  6.         /// <summary>
  7.         /// Enables inspection or modification of a message before a request message is sent to a service.
  8.         /// </summary>
  9.         /// <param name="request">The message to be sent to the service.</param>
  10.         /// <param name="channel">The WCF client object channel.</param>
  11.         /// <returns>
  12.         /// The object that is returned as the <paramref name="correlationState " /> argument of
  13.         /// the <see cref="M:System.ServiceModel.Dispatcher.IClientMessageInspector.AfterReceiveReply(System.ServiceModel.Channels.Message@,System.Object)" /> method.
  14.         /// This is null if no correlation state is used.The best practice is to make this a <see cref="T:System.Guid" /> to ensure that no two
  15.         /// <paramref name="correlationState" /> objects are the same.
  16.         /// </returns>
  17.         public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel)
  18.         {
  19.             SoapSecurityHeader header = new SoapSecurityHeader("UsernameToken-1", UserName, Password, "");
  20.  
  21.             request.Headers.Add(header);
  22.  
  23.             return header.Id;
  24.         }
  25.  
  26.         /// <summary>
  27.         /// Enables inspection or modification of a message after a reply message is received but prior to passing it back to the client application.
  28.         /// </summary>
  29.         /// <param name="reply">The message to be transformed into types and handed back to the client application.</param>
  30.         /// <param name="correlationState">Correlation state data.</param>
  31.         public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
  32.         {
  33.             var a = reply;
  34.             // Nothing special here
  35.         }
  36.     }

下面是写入Head的部分

  1. public class SoapSecurityHeader : MessageHeader
  2.     {
  3.         private readonly string _password, _username, _nonce;
  4.         private readonly DateTime _createdDate;
  5.  
  6.         public SoapSecurityHeader(string id, string username, string password, string nonce)
  7.         {
  8.             _password = password;
  9.             _username = username;
  10.             _nonce = nonce;
  11.             _createdDate = DateTime.Now;
  12.             this.Id = id;
  13.         }
  14.  
  15.         public string Id { get; set; }
  16.  
  17.         public override string Name
  18.         {
  19.             get { return "Security"; }
  20.         }
  21.  
  22.         public override string Namespace
  23.         {
  24.             get { return "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"; }
  25.         }
  26.  
  27.         protected override void OnWriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion)
  28.         {
  29.             writer.WriteStartElement("wsse", Name, Namespace);
  30.             writer.WriteXmlnsAttribute("wsse", Namespace);
  31.         }
  32.  
  33.         protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
  34.         {
  35.             writer.WriteStartElement("wsse", "UsernameToken", Namespace);
  36.             writer.WriteAttributeString("Id", "UsernameToken-10");
  37.             writer.WriteAttributeString("wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
  38.  
  39.             writer.WriteStartElement("wsse", "Username", Namespace);
  40.             writer.WriteValue(_username);
  41.             writer.WriteEndElement();
  42.  
  43.             writer.WriteStartElement("wsse", "Password", Namespace);
  44.             writer.WriteAttributeString("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
  45.             writer.WriteValue(_password);
  46.             writer.WriteEndElement();
  47.  
  48.             writer.WriteStartElement("wsse", "Nonce", Namespace);
  49.             writer.WriteAttributeString("EncodingType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary");
  50.             writer.WriteValue(_nonce);
  51.             writer.WriteEndElement();
  52.  
  53.             writer.WriteStartElement("wsse", "Created", Namespace);
  54.             writer.WriteValue(_createdDate.ToString("YYYY-MM-DDThh:mm:ss"));
  55.             writer.WriteEndElement();
  56.  
  57.             writer.WriteEndElement();
  58.         }
  59.     }

至此大功告成!

posted @ 2015-05-19 18:38  默蛇  阅读(1183)  评论(0编辑  收藏  举报