c# - 从服务访问 WCF 客户端凭据

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

我有以下对 WCF 服务的调用(使用基本身份验证):

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

client.MyServiceFunction();

在服务器上,我有:

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

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

最佳答案

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

您创建一个继承自 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

但是您可能需要指定 <message establishSecurityContext="true" />作为绑定(bind)安全性的一部分,并非所有绑定(bind)都可用,例如。基本的HTTP绑定(bind)

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

关于c# - 从服务访问 WCF 客户端凭据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22350453/

相关文章:

c# - NETSDK1073 : The FrameworkReference 'Microsoft.AspNetCore.App' was not recognized

c# - 在 JSON.NET 中反序列化 IList<Interface>

c# - XML 包装的集合不反序列化

c# - 获取嵌套集合包含另一个集合中的项目的项目

.net - 使用 C# 反序列化 Json 对象

c# - 如何使用 UIElement 依赖属性实现 WPF 用户控件?

c# - 控制台应用程序的 log4net 配置

asp.net - 字符支持问题 - 如何将较高的 ASCII 字符转换为较低的 ASCII 字符

vb.net - 正确关闭在新线程中运行循环的表单

vb.net - HttpUtility.ParseQueryString 未按预期工作