vb.net 从服务访问 WCF 客户端凭据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22350453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing WCF client credentials from the service
提问by Paul Michaels
I have the following call to a WCF service (using basic authentication):
我对 WCF 服务进行了以下调用(使用基本身份验证):
client.ClientCredentials.UserName.UserName = "username";
client.ClientCredentials.UserName.Password = "password";
client.MyServiceFunction();
On the server, I have:
在服务器上,我有:
class MyService : IMyService
{
string MyServiceFunction()
{
return GetUsernameHere();
}
}
My question is, can I access these credentials in the WCF service and, if so, how? That is, how would I implement the GetUsernameHerefunction?
我的问题是,我可以在 WCF 服务中访问这些凭据吗?如果可以,如何访问?也就是说,我将如何实现该GetUsernameHere功能?
采纳答案by NibblyPig
For this type of validation to work you must write your own validator for the username and password.
要使这种类型的验证工作,您必须为用户名和密码编写自己的验证程序。
You create a class that inherits from UserNamePasswordValidatorand specify it in your webconfig like this:
您创建一个继承自UserNamePasswordValidator并在您的 webconfig 中指定它的类,如下所示:
<serviceBehaviors>
<behavior name="CustomValidator">
<serviceCredentials>
<userNameAuthentication
userNamePasswordValidationMode="Custom"
customUserNamePasswordValidatorType=
"SomeAssembly.MyCustomUserNameValidator, SomeAssembly"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
The custom validator class will look like this:
自定义验证器类将如下所示:
public class MyCustomUserNameValidator : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
// Do your username and password check here
}
}
The password is not available outside of the validation portion of WCF so you can only retrieve it using the custom validator.
密码在 WCF 的验证部分之外不可用,因此您只能使用自定义验证器检索它。
However if you just want the username, it should be accessible via:
但是,如果您只想要用户名,则应该可以通过以下方式访问:
OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name
OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name
however you may need to specify <message establishSecurityContext="true" />as part of your binding's security, and this isn't available on all bindings eg. basicHttpBinding
但是,您可能需要将其指定<message establishSecurityContext="true" />为绑定安全性的一部分,并且这不适用于所有绑定,例如。基本Http绑定
<bindings>
<wsHttpBinding>
<!-- username binding -->
<binding name="Binding">
<security mode="Message">
<message clientCredentialType="UserName" establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>

