HTTP Authentication with Web References - authentication

I have a web reference created from the WSDL, but I'm not allowed to call the function unless I pass in the username / password; the original code for the XML toolkit was:
Set client = CreateObject("MSSOAP.SOAPClient30")
URL = "http://" & host & "/_common/webservices/Trend?wsdl"
client.mssoapinit (URL)
client.ConnectorProperty("WinHTTPAuthScheme") = 1
client.ConnectorProperty("AuthUser") = user
client.ConnectorProperty("AuthPassword") = passwd
On Error GoTo err
Dim result1() As String
result1 = client.getTrendData(expression, startDate, endDate,
limitFromStart, maxRecords
How do I add the AuthUser/AuthPassword to my new code?
New code:
ALCServer.TrendClient tc = new WindowsFormsApplication1.ALCServer.TrendClient();
foreach(string s in tc.getTrendData(textBox2.Text, "5/25/2009", "5/28/2009", false, 500))
textBox1.Text+= s;

Found it: Even if Preauthenticate==True, it doesn't do it. You have to overried the WebRequest:
protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
HttpWebRequest request;
request = (HttpWebRequest)base.GetWebRequest(uri);
if (PreAuthenticate)
{
NetworkCredential networkCredentials =
Credentials.GetCredential(uri, "Basic");
if (networkCredentials != null)
{
byte[] credentialBuffer = new UTF8Encoding().GetBytes(
networkCredentials.UserName + ":" +
networkCredentials.Password);
request.Headers["Authorization"] =
"Basic " + Convert.ToBase64String(credentialBuffer);
}
else
{
throw new ApplicationException("No network credentials");
}
}
return request;
}
Since it gets created as a partial class, you can keep the stub in a separate file and rebuilding the Reference.cs won't clobber you.

Related

Do I have to use SSL with Paypal? How do I set Paypal on Windows Azure?

I am putting online an old web application I had running like 3 years ago.
Back then everything worked and Paypal's ExpressCheckout was set perfectly.
I really cannot remember what I was doing back then but now I put my app on Windows Azure. My app is written in ASP.NET MVC5.
The following piece of code might look familiar for those of you who implemented Paypal inside your apps and its probably taken from Paypal's documentation and used for posing to Paypal's server:
/// <summary>
/// HttpCall: The main method that is used for all API calls
/// </summary>
/// <param name="NvpRequest"></param>
/// <returns></returns>
public string HttpCall(string NvpRequest) //CallNvpServer
{
string url = pendpointurl;
//To Add the credentials from the profile
string strPost = NvpRequest + "&" + buildCredentialsNVPString();
strPost = strPost + "&BUTTONSOURCE=" + HttpUtility.UrlEncode(BNCode);
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = Timeout;
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";
try
{
using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
{
myWriter.Write(strPost, 0, strPost.Length);
}
}
catch (Exception e)
{
CommonFuncs.Log(MyGlobals.LOG_FILE_DO_EXPRESS_CHECKOUT, e.Message);
return null;
/*
if (log.IsFatalEnabled)
{
log.Fatal(e.Message, this);
}*/
}
//Retrieve the Response returned from the NVP API call to PayPal
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
string result;
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}
//Logging the response of the transaction
/* if (log.IsInfoEnabled)
{
log.Info("Result :" +
" Elapsed Time : " + (DateTime.Now - startDate).Milliseconds + " ms" +
result);
}
*/
return result;
}
Now, when I'm trying to POST (here)
using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
{
myWriter.Write(strPost, 0, strPost.Length);
}
I am getting the following error message
The request was aborted: Could not create SSL/TLS secure channel.
Does it mean that I have to purchase an SSL certificate? or is there something I just need to tweek on Azure so it will work?
No need to purchase an SSL. But you can upgrade your certificate into SHA 256 and TLS 1.2. Refer to the link below.
https://www.paypal-knowledge.com/infocenter/index?page=content&id=FAQ1913
and
https://github.com/paypal/TLS-update
Thank you #PP_MTS_Steven.
I can't remember the source on SO which gave me the solution. However, all I did was to put this two lines of code:
ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
// allows for validation of SSL conversations
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
Right here:
public string HttpCall(string NvpRequest) //CallNvpServer
{
string url = pendpointurl;
//To Add the credentials from the profile
string strPost = NvpRequest + "&" + buildCredentialsNVPString();
strPost = strPost + "&BUTTONSOURCE=" + HttpUtility.UrlEncode(BNCode);
ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
// allows for validation of SSL conversations
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = Timeout;
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";
...
And things started working.

Can Field locators be used with the CoSign Signature Soap API C#

I have tried
Req.OptionalInputs.FieldLocatorOpeningPattern = "<<";
Req.OptionalInputs.FieldLocatorClosingPattern = ">>";
but sign is not replaced the space provided in pdf. Can you please provide a code sample for using the Soap API.
Please see the code sample below for using CoSign Signature SOAP API (aka SAPIWS) with CoSign Signature Locators:
public SAPISigFieldSettingsType[] getSigFieldLocatorsInPDF(
string FileName,
string UserName,
string Password)
{
//Create Request object contains signature parameters
RequestBaseType Req = new RequestBaseType();
Req.OptionalInputs = new RequestBaseTypeOptionalInputs();
//Here Operation Type is set: enum-field-locators
Req.OptionalInputs.SignatureType = SignatureTypeFieldLocators;
//Configure Create and Sign operation parameters:
Req.OptionalInputs.ClaimedIdentity = new ClaimedIdentity();
Req.OptionalInputs.ClaimedIdentity.Name = new NameIdentifierType();
Req.OptionalInputs.ClaimedIdentity.Name.Value = UserName; //User Name
Req.OptionalInputs.ClaimedIdentity.Name.NameQualifier = " "; //Domain (relevant for Active Directory environment only)
Req.OptionalInputs.ClaimedIdentity.SupportingInfo = new CoSignAuthDataType();
Req.OptionalInputs.ClaimedIdentity.SupportingInfo.LogonPassword = Password; //User Password
Req.OptionalInputs.FieldLocatorOpeningPattern = "<<";
Req.OptionalInputs.FieldLocatorClosingPattern = ">>";
//Set Session ID
Req.RequestID = Guid.NewGuid().ToString();
//Prepare the Data to be signed
DocumentType doc1 = new DocumentType();
DocumentTypeBase64Data b64data = new DocumentTypeBase64Data();
Req.InputDocuments = new RequestBaseTypeInputDocuments();
Req.InputDocuments.Items = new object[1];
b64data.MimeType = "application/pdf"; //Can also be: application/msword, image/tiff, pplication/octet-string
Req.OptionalInputs.ReturnPDFTailOnlySpecified = true;
Req.OptionalInputs.ReturnPDFTailOnly = false;
b64data.Value = ReadFile(FileName, true); //Read the file to the Bytes Array
doc1.Item = b64data;
Req.InputDocuments.Items[0] = doc1;
//Call sign service
ResponseBaseType Resp = null;
try
{
// Create the Web Service client object
DSS service = new DSS();
service.Url = "https://prime.cosigntrial.com:8080/sapiws/dss.asmx"; //This url is constant and shouldn't be changed
SignRequest sreq = new SignRequest();
sreq.InputDocuments = Req.InputDocuments;
sreq.OptionalInputs = Req.OptionalInputs;
//Perform Signature operation
Resp = service.DssSign(sreq);
if (Resp.Result.ResultMajor != Success )
{
MessageBox.Show("Error: " + Resp.Result.ResultMajor + " " +
Resp.Result.ResultMinor + " " +
Resp.Result.ResultMessage.Value, "Error");
return null;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
if (ex is WebException)
{
WebException we = ex as WebException;
WebResponse webResponse = we.Response;
if (webResponse != null)
MessageBox.Show(we.Response.ToString(), "Web Response");
}
return null;
}
//Handle Reply
DssSignResult sResp = (DssSignResult) Resp;
return Resp.OptionalOutputs.SAPISeveralSigFieldSettings;
}

Creating A Service Bus SAS Token and Consuming Relay in WinRT

I have a Service Bus Relay (WCF SOAP) I want to consume in my Windows Store App. I have written the code to create a token as well as the client which is below.
The problem is that I get an AuthorizationFailedFault returned with a faultstring "InvalidSignature: The token has an invalid signature." And I can't figure it out.
My Create Token method:
private static string CreateSasToken()
{
TimeSpan sinceEpoch = DateTime.UtcNow - new DateTime(1970,1, 1);
var expiry = Convert.ToString((int)sinceEpoch.TotalSeconds + 3600);
string stringToSign = webUtility.UrlEncode(ServiceUri.AbsoluteUri) + "\n" + expiry;
string hashKey = Encoding.UTF8.GetBytes(Secret).ToString();
MacAlgorithmProvider macAlgorithmProvider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);
BinaryStringEncoding encoding = BinaryStringEncoding.Utf8;
var messageBuffer = CryptographicBuffer.ConvertStringToBinary(stringToSign,encoding);
IBuffer keyBuffer = CryptographicBuffer.ConvertStringToBinary(hashKey,encoding);
CryptographicKey hmacKey = macAlgorithmProvider.CreateKey(keyBuffer);
IBuffer signedMessage = CryptographicEngine.Sign(hmacKey, messageBuffer);
string signature = CryptographicBuffer.EncodeToBase64String(signedMessage);
var sasToken = String.Format(CultureInfo.InvariantCulture,
"SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}",
WebUtility.UrlEncode(ServiceUri.AbsoluteUri),
WebUtility.UrlEncode(signature), expiry, Issuer);
return sasToken;
}
My Client class:
public partial class ServiceClient
{
public async Task<string> GetDataUsingDataContract(string item, string sasToken)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("ServiceBusAuthorization",sasToken);
client.DefaultRequestHeaders.Add("SOAPAction",".../GetDataUsingDataContract");
client.DefaultRequestHeaders.Add("Host", "xxxxxxxxxxx.servicebus.windows.net");
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post,ServiceUri);
var content =new StringContent(#"<s:Envelope
xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/"">
<s:Header></s:Header><s:Body>"+ item +#"</s:Body>
</s:Envelope>",System.Text.Encoding.UTF8,"application/xml");
request.Content = content;
HttpResponseMessage wcfResponse = client.SendAsync(request).Result;
HttpContent stream = wcfResponse.Content;
var response = stream.ReadAsStringAsync();
var returnPacket = response.Result;
return returnPacket;
}
}
I have been successful consuming the Relay using Http (via Fiddler) by copying an unexpired token created by Micorosft.ServiceBus in a console app.
I figured out a solution which involved both methods being wrong.
CreateSasToken method:
A minor change involved setting the hashKey variable as byte[] and not string. This line:
string hashKey = Encoding.UTF8.GetBytes(Secret).ToString();
Changed to this:
var hashKey = Encoding.UTF8.GetBytes(Secret);
This change meant that I needed to use a different method to set keyBuffer.
This line:
IBuffer keyBuffer = CryptographicBuffer.ConvertStringToBinary(hashKey,encoding);
Change to this:
IBuffer keyBuffer = CryptographicBuffer.CreateFromByteArray(hashKey);
So the new CreateSasToken method is:
private static string GetSasToken()
{
TimeSpan sinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1);
var expiry = Convert.ToString((int)sinceEpoch.TotalSeconds + 3600);
string stringToSign = WebUtility.UrlEncode(ServiceUri.AbsoluteUri) + "\n" + expiry;
var hashKey = Encoding.UTF8.GetBytes(Secret);
MacAlgorithmProvider macAlgorithmProvider =
MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);
const BinaryStringEncoding encoding = BinaryStringEncoding.Utf8;
var messageBuffer = CryptographicBuffer.ConvertStringToBinary(stringToSign,
encoding);
IBuffer keyBuffer = CryptographicBuffer.CreateFromByteArray(hashKey);
CryptographicKey hmacKey = macAlgorithmProvider.CreateKey(keyBuffer);
IBuffer signedMessage = CryptographicEngine.Sign(hmacKey, messageBuffer);
string signature = CryptographicBuffer.EncodeToBase64String(signedMessage);
var sasToken = String.Format(CultureInfo.InvariantCulture,
"SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}",
WebUtility.UrlEncode(ServiceUri.AbsoluteUri),
WebUtility.UrlEncode(signature),
expiry, Issuer);
return sasToken;
}
Service Client Class
A couple of things to note here.
In order for the request to work, the SAS Token had to be added to the header as a parameter of a AuthenticationValueHeader object. So I added the following method to my helper class (ServiceBusHelper) which held the Key, KeyName and SasToken as properties and the CreateSasToken as a method.
public static AuthenticationHeaderValue CreateBasicHeader()
{
return new AuthenticationHeaderValue("Basic", SasToken);
}
The HttpRequestMessage Content property had to be created a special way. Taking the item parameter passed in, which was a serialized WCF DataContract type I needed to do a few things to make the SOAP envelope. Rather than go through them in detail here is the entire class (one method only). I will comment on the code to handle the response immediately following.
public partial class SalesNotifyServiceClient
{
public async Task<string> GetDataUsingDataContract(string item)
{
string returnPacket = "";
string element = "";
try
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("ServiceBusAuthorization",
ServiceBusHelper.CreateBasicHeader().Parameter);
client.DefaultRequestHeaders.Add("SOAPAction",
".../GetDataUsingDataContract");
client.DefaultRequestHeaders.Add("Host",
"xxxxxxxxxx.servicebus.windows.net");
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post,
ServiceBusHelper.ServiceUri);
//Creating the request.Content
var encodedItem = item.Replace("<", "<").Replace(">", ">");
var strRequest =
#"<s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/"">
<s:Header></s:Header><s:Body><GetDataUsingDataContract xmlns=
""http://www.xxxxxxxxxx.com/servicemodel/relay""><item>" +
encodedItem +
#"</item></GetDataUsingDataContract></s:Body></s:Envelope>";
var content = new StringContent(strRequest,
System.Text.Encoding.UTF8, "application/xml");
request.Content = content;
HttpResponseMessage wcfResponse = client.SendAsync(request).Result;
HttpContent stream = wcfResponse.Content;
var response = await stream.ReadAsStringAsync();
//Handling the response
XDocument doc;
using (StringReader s = new StringReader(response))
{
doc = XDocument.Load(s);
}
if (doc.Root != null)
{
element = doc.Root.Value;
}
returnPacket = element;
}
catch (Exception e)
{
var message = e.Message;
}
return returnPacket;
}
}
In order to get at the DataContract object I had to do a few things to the response string. As you can see at the //Handling the response comment above, using StringReader I loaded the returned SOAP envelope as a string into an XDocument and the root value was my serialized DataContract object. I then deserialized the returnPacket variable returned from the method had my response object.

Using OAuthWebSecurity with Salesforce

I'm trying to get an ASP.NET MVC site to accept Salesforce as an authentication provider, but I am not having any luck. I'll start out with the IAuthenticationClient I have so far:
public class SalesForceOAuth2Client : OAuth2Client
{
private readonly String consumerKey;
private readonly String consumerSecret;
#if DEBUG
private const String BaseEndpoint = #"https://test.salesforce.com";
#else
private const String BaseEndpoint = #"https://login.salesforce.com";
#endif
private const String AuthorizeEndpoint = BaseEndpoint + #"/services/oauth2/authorize";
private const String TokenEndpoint = BaseEndpoint + #"/services/oauth2/token";
private const String RevokeEndpoint = BaseEndpoint + #"/services/oauth2/revoke";
public SalesForceOAuth2Client(String consumerKey, String consumerSecret)
: base("SalesForce")
{
if (String.IsNullOrWhiteSpace(consumerKey))
{
throw new ArgumentNullException("consumerKey");
}
if (String.IsNullOrWhiteSpace(consumerSecret))
{
throw new ArgumentNullException("consumerSecret");
}
this.consumerKey = consumerKey;
this.consumerSecret = consumerSecret;
}
protected override Uri GetServiceLoginUrl(Uri returnUrl)
{
String redirect_url = returnUrl.AbsoluteUri;
// Hack to work-around the __provider__ & __sid__ query parameters,
// but it is ultimately useless.
/*String state = String.Empty;
Int32 q = redirect_url.IndexOf('?');
if (q != -1)
{
state = redirect_url.Substring(q + 1);
redirect_url = redirect_url.Substring(0, q);
}*/
var builder = new UriBuilder(AuthorizeEndpoint);
builder.Query = "response_type=code"
+ "&client_id=" + HttpUtility.UrlEncode(this.consumerKey)
+ "&scope=full"
+ "&redirect_uri=" + HttpUtility.UrlEncode(redirect_url)
// Part of the above hack (tried to use `state` parameter)
/*+ (!String.IsNullOrWhiteSpace(state) ? "&state=" + HttpUtility.UrlEncode(state) : String.Empty)*/;
return builder.Uri;
}
protected override IDictionary<String, String> GetUserData(String accessToken)
{
// I am not sure how to get this yet as everything concrete I've
// seen uses the service's getUserInfo call (but this service relies
// heavily on a username, password, token combination. The whole point
// of using oatuh is to avoid asking the user for his/her credentials)
// more information about the original call:
// http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_calls_getuserinfo.htm
// Return static information for now
//TODO: Get information dynamically
return new Dictionary<String, String>
{
{ "username", "BradChristie" },
{ "name", "Brad Christie" }
};
}
protected override String QueryAccessToken(Uri returnUrl, String authorizationCode)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(TokenEndpoint);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
using (StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream()))
{
streamWriter.Write("grant_type=authorization_code");
streamWriter.Write("&client_id=" + HttpUtility.UrlEncode(this.consumerKey));
streamWriter.Write("&client_secret=" + HttpUtility.UrlEncode(this.consumerSecret));
streamWriter.Write("&redirect_uri=" + HttpUtility.UrlEncode(returnUrl.AbsoluteUri));
streamWriter.Write("&code=" + HttpUtility.UrlEncode(authorizationCode));
streamWriter.Flush();
}
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
if (webResponse.StatusCode == HttpStatusCode.OK)
{
using (StreamReader streamReader = new StreamReader(webResponse.GetResponseStream()))
{
String response = streamReader.ReadToEnd();
var queryString = HttpUtility.ParseQueryString(response);
return queryString["access_token"];
}
}
return String.Empty;
}
}
The primary problem is that redirect_uri != Callback Url.
Salesforce enforces the callback URL you supply in the application configuration to match exactly to the value provided in redirect_uri of QueryAccessToken. Unfortunately OAuthWebSecurity relies on DotNetOpenAuth.AspNet, and that library appends two query parameters: __provider__ and __sid__. If I try to remove those (see the hack in GetServiceLoginUrl), obviously the login fails because the hand-back doesn't know how to continue on with the request without knowing which provider to use.
To work around this I did notice that the request call accepts an optional state parameter which is (essentially) there for passing things back and forth across the request/callback. However, with the dependence on __provider__ and __sid__ being their own keys having data=__provider__%3DSalesForce%26__sid__%3D1234567890 is useless.
Is there a work-around without having to fork/recompile the Microsoft.Web.WebPages.OAuth library and modify the OAuthWebSecurity.VerifyAuthenticationCore(HttpContextBase, String) method to look at data first, then continue on to OpenAuthSecurityMananer.GetProviderName?
Also, in case the registration mattered (AuthConfig.cs):
OAuthWebSecurity.RegisterClient(
new SalesForceOAuth2Client(/*consumerKey*/, /*consumerSecret*/),
"SalesForce",
new Dictionary<String, Object>()
);
Update (11.01.2013)
I just got a response back from Salesforce. It looks like they don't know how to implement 3.1.2 of the RFC which means that any query parameters you send in with the return_uri are not only ignored, but prohibited (at least when dynamic in nature). So, it looks like I can't use a library that works on every other platform and follows the standard--i have to create my own.
Sigh.

Calling Webmethod containing byte array (as in paramaeter)parameter with ksoap2 on android

There is WEB service written on C# with next method:
[WebMethod]
public string ByteArrTest(byte[] Buffer)
{
if (Buffer == null) return "buffer is null";
else return Buffer.Length.ToString() + " is buffer length";
}
i 'ld like call this method from android device using Ksoap2 library alike belove (simplified):
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
new MarshalBase64().register(envelope);
envelope.encodingStyle = SoapEnvelope.ENC;
SoapObject request = new SoapObject(this.getNameSpace(), this.getMethodName());
PropertyInfo pi4 = new PropertyInfo();
pi4.setName("Buffer");
byte [] b="this text".getBytes();
pi4.setValue(b);
pi4.setType(byte[].class);
// request.addProperty("buffer", "bytes".getBytes);
request.addProperty(pi4);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport =
new HttpTransportSE(this.getURL());//
androidHttpTransport.call(this.getSoapAction(), envelope);
Object response = envelope.getResponse();
//next implementation
Responce always is "buffer is null"
what is incorrect or wrong?
Thanks for any attention
Posting the whole of your method in Android calling the web service would help more.
I'm using KSoap in an Android project I'm currently working on and I'm retrieving strings. Heres one of my methods modified to match what you need:
private static String NAMESPACE = "http://tempuri.org/";
private static String SOAP_ACTION = "http://tempuri.org/";
private static final String URL = "Your url link to your web services asmx file";
public static String ByteArrTestCall(byte[] t) {
String resTxt = null;
SoapObject request = new SoapObject(NAMESPACE, "ByteArrTest");
// Add the property to request object
request.addProperty("Buffer", t);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug = true;
try
{
androidHttpTransport.call(SOAP_ACTION+"ByteArrTest", envelope);
SoapPrimitive receivedString = (SoapPrimitive) envelope.getResponse();
resTxt = receivedString.toString();
}
catch(Exception e)
{
resTxt = androidHttpTransport.requestDump;
return e.toString() + resTxt;
}
return resTxt;
}