AAHN
AAHN

Reputation: 401

Generating Username Token For Soap Request

I am trying to generate SOAP Username token using C# but without success

  <wsse:UsernameToken wsu:Id='UsernameToken-1231231231123123'>
         <wsse:Username>UserName</wsse:Username>
          <wsse:Password Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText'>Password</wsse:Password>
                                             </wsse:UsernameToken>

the above one is the correct format for our SOAP endpoint but when i am trying to generate token using UsernameToken from namespace

Microsoft.Web.Services2.Security.Tokens

    UsernameToken t;
    t = new UsernameToken("UserName", "Password");
    string usernameTokenSection1 = t.GetXml(new XmlDocument()).OuterXml.ToString();

I got this result which is not working

    <wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="SecurityToken-cf96131b-1528-46a1-8f00-f61af616db91" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<wsse:Username>Username</wsse:Username>
<wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">+S3AH9NHRtOpgdxEwqIVIg==</wsse:Nonce><wsu:Created>2020-04-04T06:46:53Z</wsu:Created></wsse:UsernameToken>

Upvotes: 1

Views: 2588

Answers (1)

iSR5
iSR5

Reputation: 3498

the wsu:Id='UsernameToken-1231231231123123' attribute is Id property of UsernameToken

So, you do this :

UsernameToken t = new UsernameToken("UserName", "Password", PasswordOption.SendPlainText)
{ 
    Id = "UsernameToken-1231231231123123"                 
};

Then you can parse it in XmlDocument or XDocument which would give you the ability to adjust the elements to fit your requirements.

you can parse it like this var doc = XDocument.Parse(usernameTokenSection1);

Now, using the parsed XML, you can adjust it to your requirements. For instance you can remove Nonce and Created elements like this :

var doc = XDocument.Parse(usernameTokenSection1);

XNamespace wsu = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd";
XNamespace wsse = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";

doc.Root.Descendants(wsse + "Nonce").Remove();
doc.Root.Descendants(wsu + "Created").Remove();

Upvotes: 1

Related Questions