6

How can I issue a POST request under the context below using webclient?

I am able to successfully authenticate and retrieve a jwt token from ADFS:

using (var client = new WebClient())
{
    var data = Encoding.UTF8.GetBytes(rstXml);
    client.Headers.Add("Content-Type", "application/soap+xml; charset=utf-8");
    var responseData =
        client.UploadData($"https://{adfsServer}/adfs/services/trust/13/usernamemixed", data);
    var rstr = Encoding.UTF8.GetString(responseData);
    var xmlDoc = new XmlDocument();
    xmlDoc.LoadXml(rstr);
    var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
    nsmgr.AddNamespace("wsse",
        "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
    nsmgr.AddNamespace("wsu",
        "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
    jwt = xmlDoc.SelectSingleNode("//wsse:BinarySecurityToken", nsmgr).InnerText; // JWT
 }

How do I issue a POST request under this same context?

Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062
  • Possible duplicate of [Setting Authorization Header of HttpClient](https://stackoverflow.com/questions/14627399/setting-authorization-header-of-httpclient) – Camilo Terevinto Feb 11 '18 at 17:52
  • @CamiloTerevinto the question to which you are referring is for ```HttpClient```, not ```WebClient``` – Alex Gordon Feb 11 '18 at 18:26
  • Well, you just edited out the `HttpClient` part. It's the same, just change the name of the properties – Camilo Terevinto Feb 11 '18 at 18:27
  • Curious. why not using HttpClient? Any specific restrictions? Not saying it is impossible, just wanted to know limitations. – Nkosi Feb 11 '18 at 18:39
  • Also a little confused as to the goal. If you have succeeded in attaining a token. What is stopping you from including it in the Authorization header of subsequent calls? Just as you were able to add the content type header when authenticating, you should be able to add an Authorization Header to make authorized requests. – Nkosi Feb 11 '18 at 18:49
  • @Nkosi you are always around to help :) thank you. when you mention ... _including it int he Authorization header of subse.._ isnt this exactly what your answer is suggesting to do? – Alex Gordon Feb 11 '18 at 19:48
  • I added the answer to demonstrate that comment. yes – Nkosi Feb 11 '18 at 19:50

1 Answers1

3

Authorization header should be able to be added to the client to make authorized requests.

//Adding authorization token to header
client.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + jwt);
//Resetting content type to be sent if we wanted to POST JSON
client.Headers[HttpRequestHeader.ContentType] = "application/json; charset=utf-8";
//POST json
var json = "{ \"Key\": \"Hello World\" }";
var response = client.UploadString("__url_here__", json);

//...
Nkosi
  • 235,767
  • 35
  • 427
  • 472