wcf - 使用 System.ServiceModel.ServiceAuthenticationManager 自定义 WCF 身份验证?

标签 wcf authentication

我正在研究自定义 WCF 身份验证和授权,并发现了一些有关 UserNamePasswordValidator 和 ServiceAuthorizationManager 的文章。

我还发现了有关使用自定义System.ServiceModel.ServiceAuthenticationManager的线索(死链接),但msdn并没有告诉太多关于它(http://msdn.microsoft.com/en-us/library/system.servicemodel.serviceauthenticationmanager.aspx)。

所以我在这里:有人了解更多有关 ServiceAuthenticationManager 的信息吗?

一般来说,您将如何设置自定义 WCF 身份验证?

最佳答案

你是对的,这方面的文档根本没有帮助。

我使用这个类的方式如下。重写 Authenticate() 方法以:

  1. 从传入消息中提取身份验证 token (例如用户名/密码)
  2. 验证 token 并使用它们创建 IPrincipal 对象。这将是调用服务操作期间使用的主体。
  3. 将 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;
}

然后添加自定义授权策略

  1. 从消息中检索 IPrincipal(使用 System.ServiceModel.EvaluationContext.Current.IncomingMessageProperties 集合)。
  2. 将 IPrincipal 插入EvaluationContext.Properties 集合
  3. 根据 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/

相关文章:

c# - 主窗体出现时如何关闭登录窗体?

c# - 使用 WCF 服务和 Xamarin.Forms 将图像存储到服务器

c# - Guid 全部为 0(零)?

wcf - 从 n 层客户端遍历对象图

c# - 使用证书以编程方式实现 WCF

api - 在使用大多数 API 时,为什么它们需要两种类型的身份验证,即 key 和 secret ?

c# - HtmlAgilityPack 登录后

asp.net - 浏览器显示 "Directory Listing --/"

c# - 如何反序列化 SOAP 响应?

javascript - 同构应用程序中的用户配置文件