繁体   English   中英

如何在WCF调用的服务端获取用户名和密码?

[英]How to get the Username and Password in the service side of a WCF call?

当我使用以下代码在客户端提供凭据时:

myChannelFactory.Credentials.UserName.UserName = "username";
myChannelFactory.Credentials.UserName.Password = "password";

然后在服务器端,我看到这些凭据可用

operationContext.IncomingMessageHeaders[1]

但是有没有更方便的方法来获取UserName和密码? 我在OperationContext看到的只是属性和无类型列表的混乱,我无法找到任何指示我可以得到它的地方。

您可以使用ServiceSecurityContext上的静态Current属性来获取正在调用的操作的当前ServiceSecurityContext

然后,您可以使用PrimaryIdentity属性以获取传入凭据的用户的标识。

但是,它不会(也不应该)公开密码。 如果您确实需要密码,那么您必须下拉到消息级别并检查标题,如您所见。

这完全取决于您使用的绑定,并且没有一般答案。

例如,如果您使用NetNamedPipeBinding并执行此操作

myChannelFactory.Credentials.UserName.UserName = "username";
myChannelFactory.Credentials.UserName.Password = "password"; 

你浪费时间:客户端绑定对这些数据不起作用,它不会出现在消息中,并且在服务端根本无法访问。

如果绑定配置了指定使用用户名/密码凭据的安全选项,则绑定将仅使用此数据。 执行此操作的所有标准绑定将使用凭据进行身份验证,其结果将通过ServiceSecurityContext显示在ServiceSecurityContext如casperOne所示,并且不包括密码数据。

为了支持身份验证,数据必须携带在邮件头中的某个位置。 究竟在哪里以及以何种形式再次依赖于约束力。 不要以为你总是会在operationContext.IncomingMessageHeaders[1]找到它们。

编辑:您可以构建一个自定义绑定,为您提供所需的内容。

CustomBinding binding = new CustomBinding( ... );
binding.Elements.Insert(1, 
  SecurityBindingElement.CreateUserNameOverTransportBindingElement());

在服务端,提供UserNamePasswordValidator并配置如下凭据:

serviceHost.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = 
  System.ServiceModel.Security.UserNamePasswordValidationMode.Custom;
servicehost.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = 
  new MyUserNamePasswordValidator();

然后,用户名和密码将传递给MyUserNamePasswordValidatorValidate方法。

警告:除非您使用安全传输,否则这不是安全的身份验证机制,因为凭据在邮件头中以明文形式发送。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM