Could not create SSL/TLS secure channel - GetRequestStream() - asp.net

I am trying to integrate paypal into a web application and I've not been successful. I have tried loads of things but I keep coming back to one particular error. I am now trying to use the paypal integration wizard, and when I get the code that is provided, I get an error that says: The request was aborted: Could not create SSL/TLS secure channel.
This is the code:
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;
StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream());
The error occurs on the last line, on the objRequest.GetRequestStream()
I tried looking it up on google but I didn't find anything that worked for me.
Does anybody know what I can do to fix this?

Add the following code to your global.asax.cs Application_Started method or before calling the (HttpWebRequest)WebRequest.Create(url);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
This was caused because PayPal are changing their encryption to TLS instead of SSL. This has already been updated on the Sandbox environments but not yet on the live.
Read more:
https://devblog.paypal.com/upcoming-security-changes-notice/

I am here with the exact same problem on a different site, but for me this did not work, but the following did:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

Related

how to change dotnet core outgoing http request hostname from the default localhost

I am able to successfully send requests to a sandbox via postman, given by a provider following their specs (see images below)
Successful request (see below)
In order to do that, aside from the respective headers and parameters (see image 2) I have to add a ssl/Tls certificate (.pfx) given that the server requires a 2 way handshake so it needs SSl client certificate:
Authorization (see below).
Headers (see below)
Body (see below)
Now, I am trying to do ir programatically using dotnet core 6, but I keep running into the same problem:
And here is my code:
public static string GetAccessToken(IConfiguration _config)
{
string UserName = Environment.GetEnvironmentVariable("USER_NAME");
string Password = Environment.GetEnvironmentVariable("PASSWORD");
var client = new RestClient("https://connect2.xyz.com/auth/token");
var request = new RestRequest();
X509Certificate2 FullChainCertificate = new X509Certificate2("Path/to/Cert/cert.pfx", "test");
client.Options.ClientCertificates = new X509CertificateCollection() { FullChainCertificate };
client.Options.Proxy = new WebProxy("connect2.xyz.com");
var restrequest = new RestRequest();
restrequest.Method = Method.Get;
restrequest.AddHeader("Accept", "*/*");
restrequest.AddHeader("Cache-Control", "no-cache");
restrequest.AddHeader("Content-Type", "application/x-www-form-urlencoded");
restrequest.AddHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes($"{UserName}:{Password}")));
restrequest.AddParameter("grant_type", "client_credentials");
RestResponse response = client.Execute(restrequest);
AccessTokenPointClickCare accessToken = JsonConvert.DeserializeObject<AccessTokenPointClickCare>(response.Content);
string strToken = accessToken.access_token;
return strToken;
}
Now, as the error seems to show, it has to do with the certificates (apparently), but I don't know if something in the code is wrong, or if I'm missing something, etc...
It is worth noting that this code did run in someone else's pc with the same set-up, but of course with that person's own pfx, but for the rest, it is essentially the same, and not to mention that it does work on my postman.
Finally, as the title on this question, the only thing I can think it might also be affecting the request is the host. If I reference the postman, there is a field where I have to place the host name of the server https://connect2.xyz.com/auth/token
So made it work by changing to a new Windows 10. Researching in other Stackoverflow threads found the answer: .NET CORE 5 '''HandshakeFailure'" when making HTTPS request
So I conclude it has to do with the cyphers

Consume web API with client certificate authentication in C#

I am consuming a web api which has client certificate authentication. I have both cert.pem, key.perm files. and I tested the api's in postman successfully by importing both files in certificate tab..
it works fine. but when i try to implement that api in my asp.net web application, it shows authentication failed error. i don't know how to use both cert.pem, key.perm files in authentication part of my coding.
I tried some codings.
string url = "https://uat-api.ssg-wsg.sg/courses/runs/50331/sessions?uen=S89PB0005D&courseReferenceNumber=PA-S89PB0005D-01-Fuchun 354&sessionMonth=012021";
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12
| SecurityProtocolType.Ssl3;
X509Certificate clientCertificate = X509Certificate.CreateFromCertFile(System.Web.HttpContext.Current.Server.MapPath("~/Certificates/cert.pem"));
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format(url));
WebReq.Method = "GET";
WebReq.ClientCertificates.Add(clientCertificate);
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
using (Stream stream = WebResp.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
jsonString = reader.ReadToEnd();
}
Can anyone help me how to use both cert.pem, key.perm files in authentication part and make the api runs successfully..
Thank You.
I'm assuming that your cert.pem file is the certificate and the key.pem file contains the private key.
If you are using .net 5, you can do something like this:
var certificatePem = File.ReadAllText("cert.pem"); //you have to provide the correct path here
var key = File.RealAllText("key.pem"); //and here
var certificate = X509Certificate2.CreateFromPem(certificatePem, key);
Note the use of the new X509Certificate2 class.
if my initial asumption is not true, please post the text within the pem files (you can strip off a portion of the text, or you can gray out the relevant parts, of course)

Executing a webrequest without redirecting a page

I ran into a weird problem while using openid in asp.net. I wanted a server side logout for gmail account but without redirecting to another page.
I thought executing a web request would do that. This is my code
HttpWebRequest loHttp =
(HttpWebRequest)WebRequest.Create("https://www.google.com/accounts/Logout");
// *** Set properties
loHttp.Timeout = 10000; // 10 secs
loHttp.UserAgent = "Code Sample Web Client";
// *** Retrieve request info headers
HttpWebResponse loWebResponse = (HttpWebResponse)loHttp.GetResponse();
Encoding enc = Encoding.GetEncoding(1252); // Windows default Code Page
StreamReader loResponseStream =
new StreamReader(loWebResponse.GetResponseStream(), enc);
string lcHtml = loResponseStream.ReadToEnd();
loWebResponse.Close();
loResponseStream.Close();
But it doesn't seem to work. The gmail account is still signed in.
Is it possible to execute a webrequest with such URL?
Thanks
I think that's because HttpWebRequest is made at the server level and you are logged in in the client.
You should use an iframe to load the URL

PayPal Express Checkout returns - Security header is not valid

This has probably been asked a thousand times... But i'm sure i have all the endpoints and credentials right. It was working yesterday.
Security error:
Error no: 10002
Error message: Security header is not valid
Right now i'm testing against the sandbox server.
Whenever i try the testURL in my browser i get ACK=Success with a token, but i get "Security header is not valid" error when it runs through the code.
It was working a few hours ago but for some reason i keep getting the same error now.
using user/pwd and signature from a sandbox account
https://api-3t.sandbox.paypal.com/nvp
USER=xxxxxxxxxxxxxxxxxxxx
PWD=XXXXXXXXXXXXX
SIGNATURE=XXXXXXXXXXXXXXXXXXXXXXXXXXXXX
I have the following test code:
String testURL = "https://api-3t.sandbox.paypal.com/nvp?USER=xxxxxxxxxxxxxxxxxxxx&PWD=XXXXXXXXXXXXX&SIGNATURE=XXXXXXXXXXXXXXXXXXXXXXXXXXXXX&VERSION=84.0-2276209&PAYMENTREQUEST_0_PAYMENTACTION=Sale&PAYMENTREQUEST_0_AMT=15&RETURNURL=https%3a%2f%2fdomain.com%2fCheckout.aspx&CANCELURL=https%3a%2f%2fdomain.com%2fCheckout.aspx&METHOD=SetExpressCheckout";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(testURL);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
//Send the request to PayPal and get the response
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(testURL);
streamOut.Close();
// get resposne
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = HttpUtility.UrlDecode(streamIn.ReadToEnd());
streamIn.Close();
HTTPREsponse when code sends it
TIMESTAMP=2011-11-22T23:25:34Z&CORRELATIONID=392047cb78388&ACK=Failure&VERSION=84.000000&BUILD=2271164&L_ERRORCODE0=10002&L_SHORTMESSAGE0=Security error&L_LONGMESSAGE0=Security header is not valid&L_SEVERITYCODE0=Error
HttpResponse if i just copy paste the testURL in the browser
TOKEN=EC%2d4JW15968AV8121546&TIMESTAMP=2011%2d11%2d22T22%3a59%3a27Z&CORRELATIONID=c790299fd9ac7&ACK=Success&VERSION=84%2e000000&BUILD=2271164
I've tried not to UrlEncode the variables in the test url... same problem
thanks in advance
OK this might be a bug on Paypal's side.
if i change the testUrl from
String testURL = "https://api-3t.sandbox.paypal.com/nvp?USER=XXX&PWD=YYY&SIGNATURE=ZZZ&VERSION=.......&METHOD=SetExpressCheckout";
to
String testURL = "https://api-3t.sandbox.paypal.com/nvp?&x=y&USER=XXX&PWD=YYY&SIGNATURE=ZZZ&VERSION=.......&METHOD=SetExpressCheckout";
it works
See the bolded part with random first querystring variable.
PayPal seems to ignore the first querystring parameter when it's sent from codebehind (which would be user=xxx if there wasn’t x=y before it).

HTML scraping: Forms authentication failed for the request. The ticket supplied has expired

The ActiveForums module we're using as part of our DotNetNuke system has a bug in the XML for it's RSS feed. It doesn't correctly encode ampersands, it leaves them as & rather than encoding them as &
I've reported the bug to the company, but in the mean time I need a fix. So what I've done is create an intermediary page that makes a request to the RSS feed via a System.Net.HttpWebRequest.Create(url) and them performs a Regex.Replace to replaces any unencoded ampersands.
The problem is that when I run the code on our production server I get an exception: The remote server returned an error: (500) Internal Server Error.
The only reason I could think of was around authentication (As the server requires NTLM), however as far as I can tell I'm doing this part of it correctly. My code is shown below:
string html = string.Empty;
string url = "http://intranet.nt.avs/dnn/Default.aspx?tabid=130";
WebResponse response;
WebRequest request = System.Net.HttpWebRequest.Create(url);
request.PreAuthenticate = true;
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
response = request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()) )
{
html = sr.ReadToEnd();
}
// Clean invalid XML
html = Regex.Replace( html, "&(?!amp;|gt;|lt;|quot;|apos;)", "&", RegexOptions.Multiline | RegexOptions.IgnoreCase );
Response.ContentType = "text/xml";
Response.Write( html );
Updated: Here's what the event log says
Error code: 4005
Event message: Forms authentication failed for the request. Reason: The ticket supplied has expired

Resources