扩展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([email protected],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.     }

至此大功告成!

时间: 2025-01-02 16:38:13

扩展Wcf call security service, 手动添加 Soap Security Head.的相关文章

WCF初探-2:手动实现WCF程序

1.前言 上一篇,我们通过VS自带的模板引擎自动生成了一个wcf程序,接下来我们将手动实现一个wcf程序.由于应用程序开发中一般都会涉及到大量的增删改查业务,所以这个程序将简单演示如何在wcf中构建简单的增删改查服务.我们知道WCF是一组通讯服务框架,我将解决方案按大范围划分为服务端,客户端通过服务寄宿程序产生的代理来调用服务端的公开给客户端消费的方法.总个解决方案由五个项目工程: Service:定义服务契约接口和实现服务契约,此项目类型为类库项目 Common:通用层定义数据访问的帮助类,此

手动添加SSH支持、使用c3p0

之前做的笔记,现在整理一下:大家有耐心的跟着做就能成功: SSH(struts2.spring.hibernate) *  struts2 *  充当mvc的角色 *  hibernate dao层用hibernate技术来实现 *  spring *  spring的声明式事务管理 *  应用spring的IOC和di做到完全的面向接口编程 先添加一个数据库做测试用:使用的是mysql5.0 create database testoa default character set utf8;

WCF注册Windows Service

WCF注册Windows Service 2014-06-14 返回 在前面创建一个简单的WCF程序,我们把WCF的服务寄宿到了Host这个控制台项目中了.下面将介绍如何把WCF的服务寄宿到Windows服务中: 1. 删除原来Host控制台项目,然后在solution上右键,新建一个WindowService项目.如下图: 2.对MyFirstWindowsService项目添加对Contracts项目.Service项目和System.ServiceModel的引用. 3.将MyFristW

Cisco packet tracer 的手动添加模块

在PacketTracer 里面,路由器都是基本配置,这和真实设备是相同的 基本配置里面2620只有一个以太网口: 而2621和2811在背板上有两个以太网接口 所以,你在show run里面可以看到两个 FastEthernet0/0和FastEthernet0/1: Cisco 2811 与Cisco 2911 路由器:独特集成系统架构,提供了最高业务灵活性和投资保护.它具有内嵌加密加速和主板话音数字信号处理器(DSP)插槽:入侵的保护和防火墙功能:集成化呼叫处理和语音留言: 用于多种需求的

Xcode6中手动添加Precompile Prefix Header

Xcode5中创建一个工程的时候,系统会自动创建一个以以工程名为名字的pch(Precompile Prefix Header)文件,开发的过程中可以将广泛使用的头文件以及宏包含在该文件下,编译器就会自动的将pch文件中的头文件添加到所有的源文件中去,这样在需要使用相关类的时候不需要使用import就可以直接使用头文件中的内容,很大程度上给程序员带来了编程的便利性.但是在Xcode6中去掉Precompile Prefix Header文件. Xcode6去掉Precompile Prefix

linux 手动添加swap

Linux手动添加swap分区 用法:dd [操作数] ... 或:dd 选项 Copy a file, converting and formatting according to the operands. bs=BYTES read and write up to BYTES bytes at a time cbs=BYTES convert BYTES bytes at a time conv=CONVS convert the file as per the comma separat

在Maven仓库中手动添加Oracle11g JDBC驱动

由于Oracle授权问题,Maven3不提供Oracle JDBC driver,为了在Maven项目中应用Oracle JDBC driver,必须手动添加到本地仓库 手动添加oracle 11g JDBC 驱动  mvn install:install-file -Dfile=D:/ojdbc6.jar -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.1.0 -Dpackaging=jar 命令执行后 将D:/ojdbc6.

Android6.0+需要手动添加得权限说明

这段时间刚好在弄一个webview上传得一个功能,需要用得相机和读取文件得这么一块,刚好呢自己得小米5手机又是6.0以上得,而且现在很多手机也是6.0+的了,所以也就遇到了一些以后得要遇到得麻烦了,但是这是相对与用eclipse开发的人了,as得具体不知道不怎么弄了.6.0前大家都是在Androidmanifest文件中直接添加相关权限,但是貌似6.0后的大部分手机这样添加就没效果了,于是就需要在代码中手动得提醒添加权限了,以下就是个手动添加权限得一个函数,直接上代码: private void

手动添加模块路径

# -*- coding: utf-8 -*- #python 27 #xiaodeng #手动添加模块路径 #文件名的后缀(.py)是刻意从import语句中省略的,python会选择在搜索路径中第一个符合导入文件名的文件 # #手动添加模块路径方法 #sys.path.append(dirname)