服务代码

1.契约

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text; namespace 消息拦截实现用户名验证
{
[ServiceContract(Namespace="http://localhost/")]
public interface IService1
{
[OperationContract]
string GetData(int value); }
}

2.服务实现

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text; namespace 消息拦截实现用户名验证
{
public class Service1 : IService1
{
public string GetData(int value)
{
string msg = OperationContext.Current.RequestContext.RequestMessage.ToString();
// 注意namespace必须和ServiceContract中定义的namespace保持一致,默认是:http://tempuri.org
var ns = "http://localhost/";
var user = GetHeaderValue("user", ns);
var pwd = GetHeaderValue("pwd", ns);
// 验证失败
if (user != "Guest01" || pwd != "")
return msg += "/r/n用户名密码错误";
return msg += "/r/n" + string.Format("You entered: {0}", value);
}
private string GetHeaderValue(string name, string ns = "http://tempuri.org")
{
var headers = OperationContext.Current.IncomingMessageHeaders;
var index = headers.FindHeader(name, ns);
if (index > -)
return headers.GetHeader<string>(index);
else
return null;
}
}
}

3.服务配置(Demo中采用的是默认配置)

 <?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- 为避免泄漏元数据信息,请在部署前将以下值设置为 false 并删除上面的元数据终结点 -->
<serviceMetadata httpGetEnabled="true"/>
<!-- 要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息 -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>

客户端

1.客户端代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Channels;
using System.ServiceModel; namespace 客户端
{
class Program
{
static void Main(string[] args)
{
try
{
SR01.Service1Client sc = new SR01.Service1Client();
using (var scope = new OperationContextScope(sc.InnerChannel))
{
// 注意namespace必须和ServiceContract中定义的namespace保持一致,默认是:http://tempuri.org
var myNamespace = "http://localhost/";
// 注意Header的名字中不能出现空格,因为要作为Xml节点名。
var user = MessageHeader.CreateHeader("user", myNamespace, "Guest01");
var pwd = MessageHeader.CreateHeader("pwd", myNamespace, "");
OperationContext.Current.OutgoingMessageHeaders.Add(user);
OperationContext.Current.OutgoingMessageHeaders.Add(pwd);
string res = sc.GetData();
Console.WriteLine(res);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}

2.客户端配置

 <?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService1" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="" maxBufferPoolSize="" maxReceivedMessageSize=""
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="" maxStringContentLength="" maxArrayLength=""
maxBytesPerRead="" maxNameTableCharCount="" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:7105/Service1.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IService1" contract="SR01.IService1"
name="BasicHttpBinding_IService1" />
</client>
</system.serviceModel>
</configuration>

返回结果:

红框部分为正常返回值;其它部分为SOAP XML内容

【WCF安全】SOAP消息实现用户名验证:通过OperationContext直接添加/访问MessageHeader信息的更多相关文章

  1. WCF 学习总结5 -- 消息拦截实现用户名验证(转)

    WCF建立在基于消息的通信这一概念基础上.通过方法调用(Method Call)形式体现的服务访问需要转化成具体的消息,并通过相应的编码(Encoding)才能通过传输通道发送到服务端:服务操作执行的 ...

  2. webservice系统学习笔记5-手动构建/发送/解析SOAP消息

    手动拼接SOAP消息调用webservice SOAP消息的组成: 1.创建需要发送的SOAP消息的XML(add方法为例子) /** * 创建访问add方法的SOAP消息的xml */ @Test ...

  3. 如何在WCF中用TcpTrace工具查看发送和接收的SOAP消息

    WCF对消息加密(只对消息加密,不考虑Authorize)其实很简单,只要在server和client端的binding加入security mode为Message(还有Transport, Tra ...

  4. WCF安全:通过 扩展实现用户名密码认证

    在webSservice时代,可以通过SOAPHEADER的方式很容易将用户名.密码附加到SOAP header消息头上,用户客户端对调用客户端身份的验证.在WCF 时代,也可以通过Operation ...

  5. 【.net 深呼吸】记录WCF的通信消息

    前面老周给大伙伴们介绍了把跟踪信息写入日志文件的方法,今天咱们换个类似的话题来扯一下,对了,咱们就说说怎么把WCF的往来消息log下来吧. 尽管在现实生活中,我们不主张偷窥他人信息,不过,偷窥程序信息 ...

  6. webservice05#soap消息

    1, SOAPMessage结构图 2, SOAP消息的创建 1>前面的一个简单WebService  服务 package com.yangw.soap.service; import jav ...

  7. WCF基础之消息协定

    通常定义消息的架构,使用数据协定就够了,但是有时必须将类型精确映射到soap消息,方法两种:1.插入自定义soap标头:2.另一种是定义消息的头和正文的安全属性.消息协定通过MessageContra ...

  8. wcf中的消息模式

    1请求响应模式 a.wcf中的消息模式默认是请求响应模式 b.返回值是void默认也是请求响应模式,可返回服务端的错误信息 c.客户端在请求后,当前线程停止真到接受收服务器的响应 [Opereatio ...

  9. ajax基础语法、ajax做登录、ajax做用户名验证是否可用、ajax做关键字查询动态显示、ajax做用表格显示数据并增加操作列

    AJAX: AJAX 是一种用于创建快速动态网页的技术. 通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新.这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新.   ...

随机推荐

  1. Hungry Rabbit

    Problem C. Hungry Rabbit Input file: hungry.in Output file: hungry.out Time limit: 10 seconds Memory ...

  2. HDU 1241 油田

    这道题明明很简单但不知道为什么运行结果一直错,但提交却是对的!代码真是神奇,不过我猜测可能是提上给出的数据错了,可能提上给的数据m和n后多给了一个空格或回车,但题的数据没有 #include<s ...

  3. SpringBoot2.0整合Sharding-Jdbc

    maven: <parent> <groupId>org.springframework.boot</groupId> <artifactId>spri ...

  4. 【bzoj4806~bzoj4808】炮车马后——象棋四连击

    bzoj4806——炮 题目传送门:bzoj4806 这种题一看就是dp...我们可以设$ f[i][j][k] $表示处理到第$ i $行,有$ j $列没放炮,$ k $列只放了一个炮.接着分情况 ...

  5. [转] Android Fragment 你应该知道的一切

     转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/42628537,本文出自:[张鸿洋的博客] 很久以前写过两篇Fragment的介 ...

  6. Standard 1.1.x VM与Standard VM的区别

    在Eclipse或MyEclipse中要设置Installed JREs时,有三个选择: - Execution Environment Description - Standard 1.1.x VM ...

  7. Java中的逻辑运算符

    逻辑运算符主要用于进行逻辑运算.Java 中常用的逻辑运算符如下表所示: 我们可以从“投票选举”的角度理解逻辑运算符: 1. 与:要求所有人都投票同意,才能通过某议题 2. 或:只要求一个人投票同意就 ...

  8. NumPy IO文件操作

    NumPy - IO ndarray对象可以保存到磁盘文件并从磁盘文件加载. 可用的 IO 功能有: load()和save()函数处理 numPy 二进制文件(带npy扩展名) loadtxt()和 ...

  9. virtio guest side implementation: PCI, virtio device, virtio net and virtqueue

    With the publishing of OASIS virtio specification version 1.0, virtio made another big step in becom ...

  10. 在linux上用jmeter压测时出现很多异常java.net.NoRouteToHostException: Cannot assign requested address.

    今天压力测试时, 刚开始出现了很多异常, 都是 java.net.NoRouteToHostException: Cannot assign requested address. 经网上查资料, 是由 ...