我有以下对 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/