【问题标题】:Accessing WCF client credentials from the service从服务访问 WCF 客户端凭据
【发布时间】:2014-03-12 11:43:46
【问题描述】:

我对 WCF 服务进行了以下调用(使用基本身份验证):

client.ClientCredentials.UserName.UserName = "username";
client.ClientCredentials.UserName.Password = "password";

client.MyServiceFunction();

在服务器上,我有:

class MyService : IMyService
{
    string MyServiceFunction()
    {
         return GetUsernameHere();
    }
}

我的问题是,我可以在 WCF 服务中访问这些凭据吗?如果可以,如何访问?也就是如何实现GetUsernameHere函数?

【问题讨论】:

    标签: c# .net vb.net wcf basic-authentication


    【解决方案1】:

    要使这种类型的验证起作用,您必须为用户名和密码编写自己的验证器。

    您创建一个继承自 UserNamePasswordValidator 的类,并在您的 webconfig 中指定它,如下所示:

        <serviceBehaviors>
          <behavior name="CustomValidator">
            <serviceCredentials>
              <userNameAuthentication
                userNamePasswordValidationMode="Custom"
                customUserNamePasswordValidatorType=
     "SomeAssembly.MyCustomUserNameValidator, SomeAssembly"/>
            </serviceCredentials>
          </behavior>
        </serviceBehaviors>
    

    自定义验证器类将如下所示:

    public class MyCustomUserNameValidator : UserNamePasswordValidator
    {
        public override void Validate(string userName, string password)
        {
    
            // Do your username and password check here
    
        }
    }
    

    密码在 WCF 的验证部分之外不可用,因此您只能使用自定义验证器检索它。

    但是,如果您只想要用户名,它应该可以通过以下方式访问:

    OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name

    但是,您可能需要将 &lt;message establishSecurityContext="true" /&gt; 指定为绑定安全性的一部分,并且这并非在所有绑定上都可用,例如。基本HttpBinding

    <bindings>
      <wsHttpBinding>
        <!-- username binding -->
        <binding name="Binding">
          <security mode="Message">
            <message clientCredentialType="UserName" establishSecurityContext="true" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    

    【讨论】:

    • 我不是要验证用户名,只是访问它。我对用户名和密码的验证非常满意
    • 您可以获取用户名/密码并将它们存储在该验证器方法中的会话中。我能找到的最接近凭证的是OperationContext.Current.ServiceSecurityContext。您可能需要在绑定安全性中包含&lt;message establishSecurityContext="true" /&gt;。根据我的阅读,您无法以任何其他方式检索密码,因为它是身份验证过程的一部分。
    • @NibblyPig 使用问题的代码和您建议的自定义验证器,我的服务在启动时崩溃,因为它说它需要证书。没有证书可以做吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多