我正在研究自定义 WCF 身份验证和授权,并发现了一些有关 UserNamePasswordValidator 和 ServiceAuthorizationManager 的文章。
我还发现了有关使用自定义System.ServiceModel.ServiceAuthenticationManager的线索(死链接),但msdn并没有告诉太多关于它(http://msdn.microsoft.com/en-us/library/system.servicemodel.serviceauthenticationmanager.aspx)。
所以我在这里:有人了解更多有关 ServiceAuthenticationManager 的信息吗?
一般来说,您将如何设置自定义 WCF 身份验证?
最佳答案
你是对的,这方面的文档根本没有帮助。
我使用这个类的方式如下。重写 Authenticate() 方法以:
- 从传入消息中提取身份验证 token (例如用户名/密码)
- 验证 token 并使用它们创建 IPrincipal 对象。这将是调用服务操作期间使用的主体。
- 将 IPrincipal 对象添加到 message.Properties 集合中,以便稍后在 WCF 处理管道中使用
此时您不能只设置线程主体,因为稍后 WCF 会更改它。
ServiceAuthenticationManager.Authenticate() 方法中的代码如下所示:
public override ReadOnlyCollection<IAuthorizationPolicy> Authenticate(ReadOnlyCollection<IAuthorizationPolicy> authPolicy, Uri listenUri, ref Message message)
{
int tokenPosition = message.Headers.FindHeader("Token", "http://customnamespace.org");
string token = message.Headers.GetHeader<string>(tokenPosition);
IPrincipal user = new CustomPrincipal(token);
message.Properties["Principal"] = user;
return authPolicy;
}
然后添加自定义授权策略
- 从消息中检索 IPrincipal(使用 System.ServiceModel.EvaluationContext.Current.IncomingMessageProperties 集合)。
- 将 IPrincipal 插入EvaluationContext.Properties 集合
- 根据 IPrincipal.IsInRole() 方法提出声明
IAuthorizationPolicy() 方法中的代码如下所示
public bool Evaluate(EvaluationContext evaluationContext, ref object state)
{
IPrincipal user = OperationContext.Current.IncomingMessageProperties["Principal"] as IPrincipal;
evaluationContext.Properties["Principal"] = user;
evaluationContext.Properties["Identities"] = new List<IIdentity> { user.Identity };
IList<Claim> roleClaims = this.GetRoleClaims(user);
evaluationContext.AddClaimSet(this, new DefaultClaimSet(this.Issuer, roleClaims));
return true;
}
在服务行为配置中,您需要设置principalPermissionMode="Custom",以便WCF将IPrincipal设置为实际服务操作调用的执行线程上的主体。
<serviceAuthorization principalPermissionMode="Custom"...
关于wcf - 使用 System.ServiceModel.ServiceAuthenticationManager 自定义 WCF 身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3715778/