要使这种类型的验证起作用,您必须为用户名和密码编写自己的验证器。
您创建一个继承自 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" /> 指定为绑定安全性的一部分,并且这并非在所有绑定上都可用,例如。基本HttpBinding
<bindings>
<wsHttpBinding>
<!-- username binding -->
<binding name="Binding">
<security mode="Message">
<message clientCredentialType="UserName" establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>