惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

A
Arctic Wolf
博客园 - 聂微东
F
Fortinet All Blogs
云风的 BLOG
云风的 BLOG
小众软件
小众软件
V
Visual Studio Blog
博客园 - 三生石上(FineUI控件)
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Apple Machine Learning Research
Apple Machine Learning Research
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
The Cloudflare Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
The GitHub Blog
The GitHub Blog
Y
Y Combinator Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园_首页
L
LangChain Blog
A
About on SuperTechFans
阮一峰的网络日志
阮一峰的网络日志
I
Intezer
T
The Blog of Author Tim Ferriss
Security Latest
Security Latest
C
CXSECURITY Database RSS Feed - CXSecurity.com
Know Your Adversary
Know Your Adversary
Simon Willison's Weblog
Simon Willison's Weblog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
P
Palo Alto Networks Blog
Scott Helme
Scott Helme
S
Secure Thoughts
Spread Privacy
Spread Privacy
T
Threat Research - Cisco Blogs
Attack and Defense Labs
Attack and Defense Labs
P
Privacy & Cybersecurity Law Blog
O
OpenAI News
H
Heimdal Security Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Help Net Security
Help Net Security
C
Cyber Attacks, Cyber Crime and Cyber Security
Blog — PlanetScale
Blog — PlanetScale
GbyAI
GbyAI
G
Google Developers Blog
博客园 - Franky
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
K
Kaspersky official blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
T
Tor Project blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
Tenable Blog
Google Online Security Blog
Google Online Security Blog
PCI Perspectives
PCI Perspectives

博客园 - ruinet

WCF通用服务请求类 使用MVP模式实现B/S和C/S平台的功能通用 Microsoft.Practices.Unity依赖注入使用实例 简洁的Asp.net菜单控件 Windows Mobile无线打印的实现 使用HTML,CSS快速导出数据到Excel 软件技术网站精选 CakePHP架构入门 升级Sql Server 2000到Sql Server 2005中要注意的问题 asp.net web开发综合技能 编写第一个Silverlight程序 Saas学习 在Windows Mobile上控制输入法 - ruinet - 博客园 在Windows Mobile创建桌面快捷方式 在仿真设备中使用主机网络 CSS,JavaSript,Html实用小代码 重启PocketPC移动设备 使用Ajax控件引发性能问题 智能移动项目打包发布经验交流
WCF中使用扩展行为来验证连接的用户
ruinet · 2010-03-21 · via 博客园 - ruinet

2010-03-21 11:20  ruinet  阅读(2987)  评论()    收藏  举报

        在WCF实现安全控制的方法很多,如使用证书、windows身份认证等等。本文要介绍的是使用简单的用户名密码方式来验证,客户端在与服务端交互时附带传递用户名和密码。使用该方法的好处就是配置简单,不受环境的制约。

通过WCF中的扩展行为来将用户名和密码附加到消息头MessageHeader中,自然这样就可以在服务端通过读取IncomingMessageHeaders得到用户名和密码。

       自定义行为,自定义行为要实现:IEndpointBehavior BehaviorExtensionElement

IEndpointBehavior members:

代码

public void AddBindingParameters(ServiceEndpoint endpoint, 
            System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
            
return;
        }
public void ApplyClientBehavior(ServiceEndpoint endpoint, 
            System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
        {
            clientRuntime.MessageInspectors.Add(
new IdentityHeaderInspector());
        }
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, 
            System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
        {

        }

public void Validate(ServiceEndpoint endpoint)
        {
            
return;
        }

BehaviorExtensionElement members

代码

  public override Type BehaviorType
        {
            
get
            {
                
return typeof(AttachContextBehavior);
            }
        }
protected override object CreateBehavior()
        {
            
return new AttachContextBehavior();
        }


自定义消息检查器IClientMessageInspector,在消息检查器中添加MessageHeader附加用户名和密码:

代码

  private class IdentityHeaderInspector : IClientMessageInspector
        {
            
#region IClientMessageInspector Memberspublic void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
            {
            }
public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
            {
                MessageHeader
<string> header = new MessageHeader<string>(AppContext.UserName);
                request.Headers.Add(header.GetUntypedHeader(
"UserName""http://ruinet.cnblogs.com/username"));

                header 

= new MessageHeader<string>(AppContext.Password);
                request.Headers.Add(header.GetUntypedHeader(
"Password""http://ruinet.cnblogs.com/password"));
                
return null;
            }
#endregion

        }

然后在实现的IEndpointBehavior接口的ApplyClientBehavior行为中添加IdentityHeaderInspector

代码

public void ApplyClientBehavior(ServiceEndpoint endpoint, 
            System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
        {
            clientRuntime.MessageInspectors.Add(
new IdentityHeaderInspector());
        }

完整扩展行为代码:

代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Dispatcher;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Configuration;
using WCFSecurity.Security;namespace WCFSecurity.Security
{
    
public class AttachContextBehavior : BehaviorExtensionElement, IEndpointBehavior
    {
        
public override Type BehaviorType
        {
            
get
            {
                
return typeof(AttachContextBehavior);
            }
        }
protected override object CreateBehavior()
        {
            
return new AttachContextBehavior();
        }
#region IEndpointBehavior Memberspublic void AddBindingParameters(ServiceEndpoint endpoint, 
            System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
            
return;
        }
public void ApplyClientBehavior(ServiceEndpoint endpoint, 
            System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
        {
            clientRuntime.MessageInspectors.Add(
new IdentityHeaderInspector());
        }
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, 
            System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
        {

        }

public void Validate(ServiceEndpoint endpoint)
        {
            
return;
        }
#endregionprivate class IdentityHeaderInspector : IClientMessageInspector
        {
            
#region IClientMessageInspector Memberspublic void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
            {
            }
public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
            {
                MessageHeader
<string> header = new MessageHeader<string>(AppContext.UserName);
                request.Headers.Add(header.GetUntypedHeader(
"UserName""http://ruinet.cnblogs.com/username"));

                header 

= new MessageHeader<string>(AppContext.Password);
                request.Headers.Add(header.GetUntypedHeader(
"Password""http://ruinet.cnblogs.com/password"));
                
return null;
            }
#endregion

        }
    }
}

 在客户端的配置文件中加入扩展行为AttachContextBehavior

代码

<behaviors>
            
<endpointBehaviors>
                
<behavior name="headersMapping">
                    
<attachContextHeader/>
                
</behavior>
            
</endpointBehaviors>
        
</behaviors>
        
<extensions>
            
<behaviorExtensions>
                
<add name="attachContextHeader" type="WCFSecurity.Security.AttachContextBehavior, WCFSecurity.Security, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
            
</behaviorExtensions>
        
</extensions>

behaviorExtensions节点中加入自定义对象,然后再behavior节点指定:<attachContextHeader/>,最后在endpoint的behaviorConfiguration指定行为即可:

代码

<endpoint name="CalculateService"
    contract 
="WCFSecurity.Contracts.ICalculateService"
    address
="http://localhost:8001/CalculateService"
    binding 
="wsHttpBinding"
    bindingConfiguration 
="wsHttpBindingConfig"
    behaviorConfiguration 
="headersMapping" />

实例客户端运行时传递用名ruinet和密码88888:

代码

 static void Main(string[] args)
        {
            AppContext.UserName 
= "ruinet";
            AppContext.Password 
= "888888";

            Console.WriteLine(

"connecting host..");
            CalculateServiceProxy proxy 
= new CalculateServiceProxy();
            Console.WriteLine ( proxy.Add(
1222));

            proxy.Close();

            Console.WriteLine(

"close connect");
            Console.ReadLine(); 
        }

在服务器端接收用户名和密码:

代码

namespace WCFSecurity.Services
{
    
public class CalculateService : WCFSecurity.Contracts.ICalculateService
    {
        
public double Add(double num1, double num2)
        {
            Console.WriteLine(
"Client  Requirement is coming");int index= OperationContext.Current.IncomingMessageHeaders.FindHeader("UserName"
                
"http://ruinet.cnblogs.com/username");
            
if (index != -1)
            {
                
string userName = OperationContext.Current.IncomingMessageHeaders.GetHeader<string>("UserName"
                    
"http://ruinet.cnblogs.com/username");
                
string password = OperationContext.Current.IncomingMessageHeaders.GetHeader<string>("Password"
                    
"http://ruinet.cnblogs.com/password");

                Console.WriteLine(

"UserName:" + userName);
                Console.WriteLine(
"Password:" + password);
            }
          
return num1 + num2;
        }
    }
}

运行结果:

代码下载