我必须创建一个 WCF 服务 (ServiceWrapper),它引用另一个 WCF 服务 (RealService)。
我希望 ServiceWrapper 的客户端在身份验证请求中传递用户名/密码。
ServiceWrapper调用RealService的操作。我需要将收到的用户名/密码传递给 RealSerivce 进行身份验证,然后调用其操作。
我需要在 Http 而不是 Https(SSL/TLS) 上托管服务。
问题:如何在不使用 Https(SSL/TLS) 的情况下使用服务收到的客户端凭据对引用的服务进行身份验证?
最佳答案
您可以使用 SOAP 安全性。有两种 SecurityModes 适合您 - Message、TransportWithMessageCredential。
您应该在
<binding>
中配置安全模式(用户名)像这样的部分<security mode="TransportWithMessageCredential"> <transport clientCredentialType="" /> <message clientCredentialType="UserName" /> </security>
接下来,您应该在
<behavior>
中指定自定义验证器节<behavior name="CommonBehavior"> <serviceMetadata /> <serviceDebug includeExceptionDetailInFaults="True"/> <serviceCredentials> <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="Megatec.MasterTourService.CustomUserNameValidator, Megatec.MasterTourService"/> <serviceCertificate findValue="WCFServer" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName"/> <clientCertificate> <authentication certificateValidationMode="PeerTrust" /> </clientCertificate> </serviceCredentials> </behavior>
在您的自定义验证器中,您可以访问和存储用户名和密码,这些是作为 ServiceWrapper 的凭据提供的。
using System.ServiceModel; using System.IdentityModel.Selectors; namespace MyService { public class CustomUserNameValidator : UserNamePasswordValidator { public override void Validate(string userName, string password) { if (!(userName == "testMan" && password == "pass")) throw new FaultException("Incorrect login or password"); // save your Usermame and Password for future usage. } } }
当您需要访问 RealService 时,您可以使用用户名和密码作为凭据,如下面的示例:
private readonly Dictionary<Type, Object> channelFactoryDictionary = new Dictionary<Type, Object>(); private ChannelFactory<T> GetChannelFactory<T>() where T : class { if (channelFactoryDictionary.Keys.Contains(typeof(T))) return channelFactoryDictionary[typeof(T)] as ChannelFactory<T>; var channelFactory = new ChannelFactory<T>("*"); channelFactory.Credentials.UserName.UserName = userName; channelFactory.Credentials.UserName.Password = password; channelFactoryDictionary.Add(typeof(T), channelFactory); return channelFactory; }
关于c# - WCF:将用户名和密码传递给另一项服务(无 Https),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11548053/