我正在开发一个带有自定义 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
}