3

我正在开发一个带有自定义 USERNAME-PASSWORD 验证器的 WCF 服务。

我有一个继承自UserNamePasswordValidator的CustomUserNameValidator

我还使用了继承自IAuthorizationPolicy的CustomAuthorizationPolicy

自定义授权策略的Evaluate方法如下所示:

    // this method gets called after the authentication stage
    public bool Evaluate(EvaluationContext evaluationContext, ref object state)
    {
        // get the authenticated client identity
        IIdentity client = GetClientIdentity(evaluationContext);

        // set the custom principal
        evaluationContext.Properties["Principal"] = new CustomPrincipal(client);

        return true;
    }

正如您所看到的 - 我在每次调用Evaluate时创建一个新的CustomPrincipal对象(这在服务上调用的每个操作中都完成)。

这是我的CustomPrincipal构造函数的样子:

    public CustomPrincipal(IIdentity identity)
    {
        IdentityObject = identity;
        GetUser(IdentityObject.Name);
        EnsureRoles();
    }

GetUser和EnsureRoles方法转到SQL 数据库,以检查用户的角色。

我的问题是 - 为什么每次操作都必须发生这种情况?

为什么CustomPrincipal的创建发生在每个操作上,而不仅仅是在客户端第一次连接到服务时?

对我来说,为什么对于服务上调用的每个操作都没有意义 - “CustomPrincipal”将进入数据库并重新获取用户,以及他的所有角色......

[更新] 这是我的查询服务界面的样子:

[ServiceContract(Namespace = "http://www.my1fj.com/QueryService/2012/", SessionMode = SessionMode.Required, ProtectionLevel = ProtectionLevel.EncryptAndSign)]
public interface IQueryService
{
     // Some operations
}
4

1 回答 1

1

我希望您的服务是按呼叫服务,并且在按呼叫服务中,每次呼叫都会进行身份验证检查,但对于按会话服务,检查仅在会话开始时进行(如果打开了安全协商)。

..从这里

而不是每次都可以在服务中缓存它们时访问数据库。

更新:

服务是每次调用/每次会话/单例,由应用于服务类的InstanceContextMode属性决定。ServiceBehavior

前任。

[ServiceContract]
interface IMyContract {...}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] 
class MyService : IMyContract {...}

要了解更多信息,请查看此帖子。要了解有关该InstanceContextMode物业的更多信息,请查看

于 2012-06-18T13:06:56.497 回答