服务代码

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. SQL生成一串随机数

    SELECT RIGHT (CONVERT(VARCHAR(20),CONVERT(DECIMAL(20,15),rand())),15) AS c_random_number

  2. [LeetCode] 139 Word Break(BFS统计层数的方法)

    原题地址: https://leetcode.com/problems/word-break/description/ 题目: Given a non-empty string s and a dic ...

  3. APPIUM API整理(python)---其他辅助类

    App运行类 1.current_activity current_activity(self): 用法: print(driver.current_activity()) Retrieves the ...

  4. 在 React Native 中使用 Redux 架构

    前言 Redux 架构是 Flux 架构的一个变形,相对于 Flux,Redux 的复杂性相对较低,而且最为巧妙的是 React 应用可以看成由一个根组件连接着许多大大小小的组件的应用,Redux 也 ...

  5. NOIP 选择客栈

    描述 丽江河边有n家很有特色的客栈,客栈按照其位置顺序从1到n编号.每家客栈都按照某一种色调进行装饰(总共k种,用整数0~ k-1表示),且每家客栈都设有一家咖啡店,每家咖啡店均有各自的最低消费. 两 ...

  6. android timed gpio (linux 3.0.0) 受时钟控制的gpio【转】

    本文转载自:https://blog.csdn.net/linxi_hnh/article/details/8043417 1 路径: drivers/staging/android/timed_gp ...

  7. Hibernate关联关系映射之一对一关联关系

    人和身份证之间就是一个典型的一对一关联关系.实现一对一关联关系映射的方式有两种一种是基于外键,一种是基于主键,下面我们先看基于外键的关联方式 首先看他们的实体类 Person类 ? 1 2 3 4 5 ...

  8. LAMP服务器的搭建

    LAMP是一组构建Web应用平台的开源软件解决方案,它是一个开源套件组合.其中L:linux,A :Apache HTTP服务器,M : MySQL或MariaDB,P : perl或Python.这 ...

  9. 通过代码来调用log4net写日志

    1.使用如下配置 http://www.cnblogs.com/chucklu/p/5404813.html 2.调用 string ConfigFile; private void LoadLogC ...

  10. UNIDAC的安装

    UNIDAC的安装1.在source目录中找到对应Delphi版本目录的make.bat文件,修改其中的 set IdeDir="D:\Application\DelphiXE2指到你的de ...