WCF: Adding Nonce to UsernameToken

后端 未结 5 404
心在旅途
心在旅途 2020-12-01 06:22

I\'m trying to connect to a web service, written in Java, but there\'s something I can\'t figure out.

Using WCF and a customBinding, almost everything seems to be fi

5条回答
  •  自闭症患者
    2020-12-01 07:17

    I also had to put a UserNameHeader segment in the SOAP message header:

    
       
           
               foouser
               foopass
           
       
       
          
       
    
    

    This was accomplished with a custom message header:

    public class UserNamePasswordHeader : MessageHeader
    {
        private readonly string _serviceUserEmail;
        private readonly string _serviceUserPassword;
    
        public UserNamePasswordHeader(string serviceUserEmail, string serviceUserPassword)
        {
            this._serviceUserEmail = serviceUserEmail;
            this._serviceUserPassword = serviceUserPassword;
        }
    
        public override string Name
        {
            get { return "UserNameHeader"; }
        }
    
        public override string Namespace
        {
            get { return "urn:bar:services"; }
        }
    
        protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
        {
            writer.WriteElementString("UserName", _serviceUserEmail);
            writer.WriteElementString("Password", _serviceUserPassword);
        }
    }
    

    Other tags, such as Nonce and Created, could easily be added.

    The class is used as follows:

    var service = new BarServiceClient();
    service.ClientCredentials.ClientCertificate.Certificate = MessageSigningCertificate;
    
    using (new OperationContextScope(service.InnerChannel))
    {
        OperationContext.Current.OutgoingMessageHeaders.Add(
          new UserNamePasswordHeader(serviceUserEmail, serviceUserPassword));
    
        try
        {
            var response = service.GetUserList();
            return response;
        }
        finally
        {
            service.Close();
        }
    }
    

    Note: MessageSigningCertificate is an X.509 certificate, I read it from a file:

    private static X509Certificate2 LoadCertificateFromFile(string pfxFilePath, string privateKeyPassword)
    {
        // Load the certificate from a file, specifying the password
        var certificate = new X509Certificate2(pfxFilePath, privateKeyPassword);
        return certificate;
    }
    

提交回复
热议问题