2010-08-11 49 views
2

目前我有一项服务使用UserNamePasswordValidator来验证客户端用户。验证代码如下:WCF UserNamePasswordValidator是否需要检查PrimaryIdentity.IsAuthenticated?

public override void Validate(String userName, String password) 
    { 
     if (userName == null) || (password == null) 
      throw new FaultException("Username and/or password not specified."); 
     if (userName != "test") && (password != "tset") 
      throw new FaultException("Invalid username and/or password."); 
    } 

正如您所看到的,当出现错误时,代码将始终引发异常。

现在的问题 - 是否有任何理由我应该检查ServiceSecurityContext.Current.PrimaryIdentity.IsAuthenticated是否在我的OperationContract函数中是否属实?例如,

public interface IMyService 
    { 
     [OperationContract] 
     void myOpContract(); 
    } 

    public class MyService : IMyService 
    { 
     public void myOpContract() 
     { 
      // Do I really need this conditional statement? 
      if (ServiceSecurityContext.Current.PrimaryIdentity.IsAuthenticated) 
       // Proceed as expected 
      else 
       // Fail? 
     } 
    } 

任何帮助将不胜感激。

回答

1

从本文中的几条评论 - Silverlight 3: Securing your WCF service with a custom username/password authentication mechanism和各种测试 - if ([...]PrimaryIdentity.IsAuthenticated)部分不是必需的。抛出UserNamePasswordValidator内部的错误会中止安全协商。

但是,代表作者的一个绝妙想法是,如果将来添加了新的绑定(连接类型)而没有安全性,则将if ([...]PrimaryIdentity.IsAuthenticated)条件语句保留就位有帮助。