代码改变世界

Win7下基于消息安全模式的WCF托管(IIS与WinForm)

2011-03-25 18:02  刘少侠  阅读(409)  评论(0编辑  收藏  举报
1:实现一个服务……
2:实现一个自定义用户名和密码验证
public class ForeverUserNamePasswordValidator : UserNamePasswordValidator
    {
        
internal static dynamic form;
        
public override void Validate(string userName, string password)
        {
            
if (userName != "juejue" || password != "1984")
            {
                form.AppendLog(
string.Format("UserName:{0},Pwd:{1} is not correct!", userName, password));
                
throw new System.IdentityModel.Tokens.SecurityTokenException("Incorrect Username or Password(密码或用户名错误!)");
            }
        }
    }
3:生成证书
(1)WinForm
makecert -r -pe -n "CN=ForeverWinForm" -ss My -sky exchange
 然后将证书导出,安装到受信任区(Internet 选项)
(2)IIS
makecert -r -pe -sr LocalMachine -n "CN=ForeverIIS" -ss My -sky exchange
然后将证书导出,安装到受信任区(Internet 选项)
  
4:配置
(1)WinForm
<!-- 服务器凭证设置 -->
                    
<serviceCredentials>
                        
<serviceCertificate x509FindType="FindBySubjectName" findValue="ForeverWinForm" 
                                      storeLocation
="CurrentUser"/>
                        
<userNameAuthentication userNamePasswordValidationMode="Custom" 
                            customUserNamePasswordValidatorType
="ForeverUserNamePasswordValidator,WcfServiceIISHost"/>
                    
</serviceCredentials>
(2)IIS(无svc托管)(在IIS7下建立App,Web.Config配置如下)
                    <serviceCredentials>
                        
<serviceCertificate x509FindType="FindBySubjectName" 
                                      findValue
="ForeverIIS" storeLocation="LocalMachine"/>
                        
<userNameAuthentication userNamePasswordValidationMode="Custom" 
                                        customUserNamePasswordValidatorType
="ForeverUserNamePasswordValidator,WcfServiceIISHost"/>
                    
</serviceCredentials>
                
</behavior>
            
</serviceBehaviors>
        
</behaviors>
        
<serviceHostingEnvironment multipleSiteBindingsEnabled="true">
            
<serviceActivations>
                
<add relativeAddress="f4.svc" service="Service.CalculatorService"/>
            
</serviceActivations>
        
</serviceHostingEnvironment>
        
<services>
            
<service name="MyFirstWcf.Service.CalculatorService">
                
<endpoint binding="wsDualHttpBinding" contract="Interface.ICalculator"></endpoint>
            
</service>
        
</services>
  
5:最后一步设置(否则会提示密钥集不存在)
Win Xp /2003:在C:\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA下为文件夹 MachineKeys 添加Everyone 并赋予浏览权限
Win 7 /Vista /2008: 在C:\ProgramData\Microsoft\Crypto\RSA 目录下为文件夹 MachineKeys 添加Everyone 并赋予浏览权限
6:客户端引用,设置凭证中相应的用户名和密码,OK!
cc.ClientCredentials.UserName.UserName = "juejue";