C# - Object as parameter in SOAP POST request (Basic Auth) - c#

I have to make a SOAP POST request to create an event in a C# application.
The events manager service is available at this endpoint:
https://eu3.provider.com/eTech/services/cxf/v6/BusinessEventManager
This endpoint uses a SOAP 1.2 binding (Document/literal) with MTOM, and offers the following security policies:
•HTTP Basic Auth through a secured channel (https) in Base64.
The method which creates the event is createEvents(BusinessEvent[], WSEntry[]), and it hasn't username and password attributes.
And now, this is my code:
// Creating the BusinessEvent[] object:
BusinessEventManagerWebReference.businessEvent[] myBusinessEvent = new BusinessEventManagerWebReference.businessEvent[1];
myBusinessEvent[0] = new BusinessEventManagerWebReference.businessEvent();
myBusinessEvent[0].id = "myBusinessEvent";
BusinessEventManagerWebReference.coreData cd = new BusinessEventManagerWebReference.coreData();
cd.creationDate = DateTime.Now;
cd.orderingCustomer = "Cliente";
cd.description = "Descripcion";
BusinessEventManagerWebReference.externalReferentialData externalRFD = new BusinessEventManagerWebReference.externalReferentialData();
externalRFD.customerName = "Nombre Cliente";
externalRFD.equipmentName = "Equipo";
cd.referentialData = externalRFD;
myBusinessEvent[0].coreData = cd;
BusinessEventManagerWebReference.location myLocation = new BusinessEventManagerWebReference.location();
myLocation.address = "Direccion";
myLocation.city = "Ciudad";
myLocation.description = "Direccion";
externalRFD.location = myLocation;
// Creating the WebRequest
WebRequest myRequest = WebRequest.Create("https://eu3.provider.com/eTech/services/cxf/v6/BusinessEventManager");
myRequest.Method = "POST";
string usernamePassword = "myuser" + ":" + "mypassword";
usernamePassword = Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword));
CredentialCache mycache = new CredentialCache();
myRequest.Credentials = mycache;
myRequest.Headers.Add("Authorization", "Basic " + usernamePassword);
However, at this point I don't know how to combine my WebRequest, my BusinessEvent object and the createEvents method for creating the event... Should I pass the BusinessEvent object as a parameter? Should I convert it to XML format before calling WebRespose()??
Any help please??
Thanks a lot!!

Related

C# Consuming web service wsdl with access token

I'm trying to consume a WSDL web service and it requires an access token to be sent in the header. However, I keep getting a 401 error and I'm not sure if I am injecting the token correctly.
Heres a snippet of the code:
var client = new WsldClient();
var operationContext = new OperationContext(client.InnerChannel);
using (new OperationContextScope(operationContext))
{
var httpRequestProperty = new HttpRequestMessageProperty();
httpRequestProperty.Headers[HttpRequestHeader.Authorization] = "Bearer " + accessToken
operationContext.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
client.SomeMethod();
}
This returns a 401 error.
You can try the following code:
var client = new MyClient();
client.ClientCredentials.UserName.UserName = "username";
client.ClientCredentials.UserName.Password = "password";
var httpRequestProperty = new HttpRequestMessageProperty();
httpRequestProperty.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(client.ClientCredentials.UserName.UserName + ":" + client.ClientCredentials.UserName.Password));
var context = new OperationContext(ormClient.InnerChannel);
using (new OperationContextScope(context))
{
context.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
return await client.SomeMethod();
}
Authorization Header is missing in Http request using WCF
http://plainoldstan.blogspot.com/2008/07/avoid-http-401-roundtrip-with-adding.html

SquareUp Request token: Forbidden

I'm working in .NET 4.6.2 and had binding issues when trying to reference the Square.Connect library which is Standard 2.0 so I'm trying to manually code things.
public ActionResult RequestToken(string code)
{
if (!string.IsNullOrEmpty(code))
{
string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/";
SquareUpRequest squareUpRequest = new SquareUpRequest()
{
client_id = "Application ID (Not sandbox)",
client_secret = "Personal Access Token",
code = code
};
var client = new RestSharp.RestClient(baseUrl);
var request = new RestSharp.RestRequest("https://connect.squareup.com/oauth/token", RestSharp.Method.POST);
request.RequestFormat = RestSharp.DataFormat.Json;
request.AddBody(squareUpRequest);
request.AddHeader("Authorization", "Client OAuthApplicationSecret");
var response = client.Execute(request);
}
return View();
}
I'm assuming that I can request a token many times. SquareUpRequest is a custom class.
Do you seen anything incorrect?
Wow. I just noticed after a few hours of hell that:
var request = new RestSharp.RestRequest("https://connect.squareup.com/oauth/token", RestSharp.Method.POST);
should be
var request = new RestSharp.RestRequest("https://connect.squareup.com/oauth2/token", RestSharp.Method.POST);

HP ALM 12.21 REST API - 401 Unauthorized - C#

I am trying to use the API against our ALM 12.21 server, but always ends up with "401 Unauthorized". It seems that I get the auth cookie back correctly, but when I try to do something after that I am unauthorized.
I use this the get this to get auth cookie (seems to work):
HttpWebRequest myauthrequest = (HttpWebRequest)WebRequest.Create("https://server/qcbin/authentication-point/alm-authenticate");
string AuthenticationXML = #"<alm-authentication>
<user>username</user>
<password>password</password>
</alm-authentication>";
byte[] Requestbytes = Encoding.UTF8.GetBytes(AuthenticationXML);
myauthrequest.Method = "POST";
myauthrequest.ContentType = "application/xml";
myauthrequest.ContentLength = Requestbytes.Length;
myauthrequest.Accept = "application/xml";
Stream RequestStr = myauthrequest.GetRequestStream();
RequestStr.Write(Requestbytes, 0, Requestbytes.Length);
RequestStr.Close();
HttpWebResponse myauthres = (HttpWebResponse)myauthrequest.GetResponse();
var AuthenticationCookie = myauthres.Headers.Get("Set-Cookie");
AuthenticationCookie = AuthenticationCookie.Replace(";Path=/;HTTPOnly", "");
I am not sure if the .Replace is needed. Just read it somewhere. I get 401 both with or without it though, when trying to do subsequent requests.
Trying e.g. this after getting auth cookie:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://server/qcbin/rest/domains/FS/projects/P3602_SLS_Project/defects/1");
req.Method = "GET";
req.ContentType = "application/xml";
req.Accept = "application/octet-stream";
req.Headers.Set(HttpRequestHeader.Cookie, AuthenticationCookie);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
Stream RStream2 = res.GetResponseStream();
XDocument doc = XDocument.Load(RStream2);
Which fails with 401.
Anyone have complete working code for the ALM 12.21 REST API?
You need two main cookies to get the ALM REST API works perfectly.
LWSSO_COOKIE_KEY
QCSession
almURL = "https://..com/qcbin/"
authEndPoint = almURL + "authentication-point/authenticate"
qcSessionEndPoint = almURL + "rest/site-session"
After you get successful response for authEndPoint you will get the LWSSO_COOKIE_KEY
Use that cookie in your next request to qcSessionEndPoint, it should give you QCSession cookie.
Use both LWSSO_COOKIE_KEY and QCSession cookies in your subsequent requests to get data from ALM.
I see that you are using octet-stream to get the defect response. When I checked the documentation, it can return one of the following types.
"application/xml"
"application/atom+xml"
"application/json"
Just in case, if you need to see some working implementation in python, here it is https://github.com/macroking/ALM-Integration/blob/master/ALM_Integration_Util.py
It may give you some idea.
Thank you #Barney. You sent me in the correct direction :-) For anyone interested, I managed it like this, e.g. for getting defect ID 473:
Logging on to create a CookieContainer and then use that to do the actual ALM data fetch:
private void button1_Click(object sender, EventArgs e)
{
string almURL = #"https://url/qcbin/";
string domain = "domain";
string project = "project";
CookieContainer cookieContainer = LoginAlm2(almURL, "username", "password", domain, project);
HttpWebRequest myWebRequest1 = (HttpWebRequest)WebRequest.Create(almURL + "/rest/domains/" + domain + "/projects/" + project + "/defects/473");
myWebRequest1.CookieContainer = cookieContainer;
myWebRequest1.Accept = "application/json";
WebResponse webResponse1 = myWebRequest1.GetResponse();
StreamReader reader = new StreamReader(webResponse1.GetResponseStream());
string res = reader.ReadToEnd();
}
public CookieContainer LoginAlm2(string server, string user, string password, string domain, string project)
{
//Creating the WebRequest with the URL and encoded authentication
string StrServerLogin = server + "/api/authentication/sign-in";
HttpWebRequest myWebRequest = (HttpWebRequest)WebRequest.Create(StrServerLogin);
myWebRequest.Headers[HttpRequestHeader.Authorization] = "Basic " + Base64Encode(user + ":" + password);
WebResponse webResponse = myWebRequest.GetResponse();
CookieContainer c = new CookieContainer();
Uri uri = new Uri(server);
string StrCookie = webResponse.Headers.ToString();
string StrCookie1 = StrCookie.Substring(StrCookie.IndexOf("LWSSO_COOKIE_KEY=") + 17);
StrCookie1 = StrCookie1.Substring(0, StrCookie1.IndexOf(";"));
c.Add(new Cookie("LWSSO_COOKIE_KEY", StrCookie1) { Domain = uri.Host });
//Then the QCSession cookie
string StrCookie2 = StrCookie.Substring(StrCookie.IndexOf("QCSession=") + 10);
StrCookie2 = StrCookie2.Substring(0, StrCookie2.IndexOf(";"));
c.Add(new Cookie("QCSession", StrCookie2) { Domain = uri.Host });
//Then the ALM_USER cookie
string StrCookie3 = StrCookie.Substring(StrCookie.IndexOf("ALM_USER=") + 9);
StrCookie3 = StrCookie3.Substring(0, StrCookie3.IndexOf(";"));
c.Add(new Cookie("ALM_USER", StrCookie3) { Domain = uri.Host });
//And finally the XSRF-TOKEN cookie
string StrCookie4 = StrCookie.Substring(StrCookie.IndexOf("XSRF-TOKEN=") + 12);
StrCookie4 = StrCookie4.Substring(0, StrCookie4.IndexOf(";"));
c.Add(new Cookie("XSRF-TOKEN", StrCookie4) { Domain = uri.Host });
return c;
}
Works like a charm :-)

RestSharp - Authorization Header not coming across to WCF REST service

I am trying to call a locally hosted WCF REST service over HTTPS with basic auth.
This works and the Authorization header comes thru just fine and all is happy:
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertficate;
var request = (HttpWebRequest)WebRequest.Create("https://localhost/MyService/MyService.svc/");
request.Method = "GET";
request.ContentType = "application/json";
request.Headers.Add(
System.Net.HttpRequestHeader.Authorization,
"Basic " + this.EncodeBasicAuthenticationCredentials("UserA", "123"));
WebResponse webResponse = request.GetResponse();
using (Stream webStream = webResponse.GetResponseStream())
{
if (webStream != null)
{
using (StreamReader responseReader = new StreamReader(webStream))
{
string response = responseReader.ReadToEnd();
}
}
}
When I try to use RestSharp however, the Authorization header never comes thru on the request:
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertficate;
var credentials = this.EncodeBasicAuthenticationCredentials("UserA", "123");
var client = new RestSharp.RestClient("https://localhost/MyService/MyService.svc/");
var restRq = new RestSharp.RestRequest("/");
restRq.Method = Method.GET;
restRq.RootElement = "/";
restRq.AddHeader("Authorization", "Basic " + credentials);
var restRs = client.Execute(restRq);
What am i doing wrong with the RestSharp method?
I know that the AddHeader method works because this:
restRq.AddHeader("Rum", "And Coke");
will come thru, only "Authorization" seems stripped out/missing.
instead of adding the header 'manually' do the following:
var client = new RestSharp.RestClient("https://localhost/MyService/MyService.svc/");
client.Authenticator = new HttpBasicAuthenticator("UserA", "123");
I used milano's answer to get my REST service call to work (using GET)
Dim client2 As RestClient = New RestClient("https://api.clever.com")
Dim request2 As RestRequest = New RestRequest("me", Method.GET)
request2.AddParameter("Authorization", "Bearer " & j.access_token, ParameterType.HttpHeader)
Dim response2 As IRestResponse = client2.Execute(request2)
Response.Write("** " & response2.StatusCode & "|" & response2.Content & " **")
The key was making sure there was a space after the word 'Bearer' but this may apply to any type of custom token authorization header
You have to use ParameterType.HttpHeader parameter:
request.AddParameter("Authorization", "data", ParameterType.HttpHeader);
I was able to get the response from my rest API using this piece of code:
My API was returning server error and I used:
request.AddHeader("Authorization", $"Bearer {accessToken}");
var request = new RestRequest("/antiforgerytokensso", Method.Get);
restClient.Authenticator = new JwtAuthenticator(accessToken);
var response = await restClient.ExecuteAsync(request);
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));

Authenticate against PHP webservice using C#

Here is the sample code for PHP Webservice client that works:
$options = array();
$options['trace'] = 1;
$options['login'] = 'username';
$options['password'] = 'password';
$client = new SoapClient("http://wsurl.com/pt/wsdl", $options);
I would like to access this webservice using c# but having a hard time doing the authentication. Do I need to explicitly set the soap headers or there is a built in way to send credentials in .NET
There are two ways to do this because servers handle authentication differently. First you could use something like this:
var req = WebRequest.Create(<your url>);
NetworkCredential creds = new NetworkCredential(<username>, <password>);
req.Credentials = creds;
var rep = req.GetResponse();
However if you need an actual Authroization header you will want to use this code
public void SetBasicAuthHeader(WebRequest req, String userName, String userPassword)
{
string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
req.Headers["Authorization"] = "Basic " + authInfo;
}
And then your request code becomes
var req = WebRequest.Create(<your url>);
SetBasicAuthHeader(req, username, password);
rep = req.GetResponse();
Let me know if you have any questions.
If you add a service reference in your C# project, you can just call your service like this:
var proxy = new YourServiceClient();
proxy.ClientCredentials.UserName.UserName = "username";
proxy.ClientCredentials.UserName.Password = "password";
More information can be found here: http://msdn.microsoft.com/en-us/library/ms733775.aspx.

Categories

Resources