【问题标题】:WCF - Why does 'CustomAuthorizationPolicy' create a 'CustomPrincipal' on every operation?WCF - 为什么“CustomAuthorizationPolicy”在每个操作上都创建一个“CustomPrincipal”?
【发布时间】:2012-06-18 10:14:55
【问题描述】:

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

我有一个继承自 UserNamePasswordValidatorCustomUserNameValidator

我还使用继承自 IAuthorizationPolicyCustomAuthorizationPolicy

自定义授权策略的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();
    }

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

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

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

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

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

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

【问题讨论】:

    标签: wcf authorization wcf-authentication


    【解决方案1】:

    我希望您的服务是每次调用服务,并且在每次调用服务中,每次调用都会进行身份验证检查,但在每次会话服务的情况下,检查仅在会话开始时进行(如果启用了安全协商开)。

    ..来自here

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

    更新:

    服务是按调用/按会话/单例由应用于服务类的ServiceBehaviorInstanceContextMode 属性决定的。

    例如

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

    要了解更多信息,请查看此post。 要了解有关InstanceContextMode 属性的更多信息,请查看this

    【讨论】:

    • 我已经更新了我的问题以显示我的服务接口是什么样的。我相信这意味着它是默认的“PerCall”,对吧? (或者“SessionMode=Required”是否意味着它不是?)
    • 所以我知道我使用的是默认的“PerCall”模式。
    猜你喜欢
    • 2023-04-10
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-09
    相关资源
    最近更新 更多