HttpWebrequest Authentication failed because the connection could not be reused - soap

I'm getting Authentication failed because the connection could not be reused while using soap request.
var credentials = new NetworkCredential();
HttpWebRequest webRequest =
(HttpWebRequest)WebRequest.Create(_configuration.GetSection("RxConfig:Url").Value);
The same code is working in .netcore 2.1. This issue occured after I migrated to .net core 3.1.

I found solution to answer.
webRequest.KeepAlive = true;
Once I used keepalive=true the error is gone.
Hope this answer helps someone looking for answer.

Related

Unable to access Rest URL using scalaj-Http client with SSL certificates(JKS File)

I am new to Scala. I am trying to access REST API URl and trying to get json data from there using Scalaj-Http with Spark framework in local vm(Intellij). But with the following Code I am always getting Http error code 401 from code and the server log is responding with "new ssl session,TLS V1.2 No Client Cert.
The jks file that I am using seems ok with proper SSL Handshake and its installed on server side.
val url = "https://abcdef:1234/api/v1/get?q=abc"
val alias ="xxxxxx-1234 yyyyy"
val sslFactory = SSLFactory.builder()
.withIdentityMaterial("abc.jks","pass".tocharArray)
.withTrustMaterial("abc.jks","pass".tocharArray)
.withClientIdentityRoute(alias,url)
.build()
val optn = HttpOptions.sslSocketFactory(sslfactory.getSslSocketfactory)
val res = Http(url) //Here getting 401 res.code
.option(optn)
.option(HttpOptions.allowUnsafeURL)
.asString
Tried everything but unable to solve. Kindly help please
I got the code working as I have to discard this option option(HttpOptions.allowUnsafe
URL)
Thanks

Getting connection timeout error while calling get access token Microsoft Graph API through REST POST call

I am trying to get access token from https://login.microsoftonline.com/{tenentname}/oauth2/v2.0/token endpoints though HttpClient post request. Applied required 4 parameters/headers with the same.
But I am getting connection timed out. Connection will be retried using another IP address (after trying with 7 different IP address) getting Shutdown connection error. Connection discarded.
Please find below code snippet.
HttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
HttpPost post = new HttpPost("https://login.microsoftonline.com/{tenentname}/oauth2/v2.0/token");
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("grant_type", "client_credentials"));
urlParameters.add(new BasicNameValuePair("client_id", {id_value}));
urlParameters.add(new BasicNameValuePair("client_secret", {secret_value}));
urlParameters.add(new BasicNameValuePair("scope", "https://graph.microsoft.com/.default"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
post.setHeader("Content-type", "application/x-www-form-urlencoded");
ClosableHttpClinet httpClient = HttpClients.custom().setConnectionManager(poolingConnManager).build();
ClosableHttpResponse response = httpClinet.execute(post);
System.out.println(EntityUtils.toString(response.getEntity()));
Same its worked with Postman without any proxy setting, I am getting proper response in Postman.
Please assist on the same.
Instead of using HTTPClient, i tried with Microsoft Graph Client (you can download from NuGet) and it worked for me. So i would suggest you to follow the steps.
Install the SDK
Configure the GraphClient
Make the call.
Also with specific to ivy dependency, here's the related thread.

Call to TLS 1.2 server with RestSharp works in console app, not in Xamarin Forms

I am communicating with a server that uses mutual TLS v1.2. I have been able to make this request in a c# console application, but when I copy this exact code to Xamarin forms, my RestClient gives me an exception: "Connection reset by peer" after a few seconds.
The code:
var client = new RestClient("https://api-sandbox.rabobank.nl/openapi/sandbox/payments/account-information/ais/v3/accounts");
ServicePointManager.Expect100Continue = true;
ServicePointManager.DefaultConnectionLimit = 9999;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
client.ClientCertificates = new X509CertificateCollection() { certificate };
client.Proxy = new WebProxy();
var request = new RestRequest(Method.GET);
var response = client.Execute(request);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Content);
I am unable to share my API keys and such, for obvious reasons. These are added through headers and are removed from the code snippet.
Things I have tried:
I checked if the projects are set to use TLS 1.2, both iOS and Android are.
I tried this in simulators and on real devices
I tried using this library, but whenever I try to add the certificate to the clientcertificate list of the handler, I get a NotImplementedException thrown.

ASP double hop request in kerberos delegation scenario

Please help!
I need my asp application to request remote systems with credentials of impersonated user. But always get 401 Unauthorized errors.
I made all configurations from here: https://support.microsoft.com/en-us/help/810572/how-to-configure-an-asp-net-application-for-a-delegation-scenario
Kerberos is configured and working in my app and my test remote app(i see kerberos tickets in fiddler). Delegation, spns and everything is configured.
Thats my code usnig System.Net.Http.httpclient:
HttpClientHandler handler = new HttpClientHandler()
{
UseDefaultCredentials = true,
PreAuthenticate = true
};
using (HttpClient client = new HttpClient(handler))
{
client.DefaultRequestHeaders.Accept.Clear();
var method = new HttpMethod("GET");
var request = new HttpRequestMessage(method, "http://testdelegationapp.avp.ru/");
var response = client.SendAsync(request).Result;
}
In fact http request is made by Apppool account (I get 401 error when restricting access to Apppool account in remote app IIS)
Here: How to get HttpClient to pass credentials along with the request?
is claimed that HttpClient cant pass security token to another thread, and its better to use synchronous methods of System.Net.WebClient
Code using webclient:
var wi = (WindowsIdentity)HttpContext.User.Identity;
var wic = wi.Impersonate();
try
{
string URI = "http://testdelegationapp.avp.ru/";
using (WebClient wc = new WebClient())
{
wc.UseDefaultCredentials = true;
string response = wc.DownloadString(URI);
}
}
finally
{
wic.Undo();
}
Result is even worse, the same 401 error, but in fiddler i can see that webclient using NTLM ticket to get to remote app!
Configuring of flowing tokens throw threads from here :Unable to authenticate to ASP.NET Web Api service with HttpClient
doesnt help either. SecurityContext.IsWindowsIdentityFlowSuppressed() is false.
WindowsIdentity.GetCurrent().Name and Thread.CurrentPrincipal.Identity.Name shows impersonated user as it should be.
All that time problem was in chrome browser, by default it prohobits kerberos delegation. You shoud add the following to registry:
Path: HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome ;
string: AuthNegotiateDelegateWhitelist ;
value: *.avp.ru
So, now my working configuration is
HttpClient for web requests.
ASP impersonation ON in IIS if you want to execute all your app under
delegated credentials. If you want method specific delegation, then use:
var wi = (WindowsIdentity)HttpContext.User.Identity;
var wic = wi.Impersonate();
wic.Undo();
HttpClient executes request in another thread , so in aspnet_config.config we need following changes:
<legacyImpersonationPolicy enabled="false"/>
<alwaysFlowImpersonationPolicy enabled="true"/>
You can find aspnet_config.config in:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet.config
C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet.config
C:\Windows\Microsoft.NET\Framework64\v2.0.50727\aspnet.config
C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet.config

SASL authorization failing while connecting to XMPP server

I am trying to connect to gmail using SMACK API through XMPP server. but getting the
error : SASL authentication failed using mechanism PLAIN
you can check a glimpse of code. I got it from net only
ConnectionConfiguration connConfig = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
connection = new XMPPConnection(connConfig);
connection.connect();
SASLAuthentication.supportSASLMechanism("PLAIN", 0);
I checked in the smack debug window. it says in XML :
< invalid-authzid />
I am already having account on gmail and my gtalk is also running.
You need to set the authentication before you connect viz
SASLAuthentication.supportSASLMechanism("PLAIN", 0);
must appear before connection.connect().
See my blog.
ConnectionConfiguration cc = new ConnectionConfiguration(
"vietnam.agilemobile.com", 5222, vietnam.agilemobile.com");
XMPPConnection connection = new XMPPConnection(cc);
try {
SASLAuthentication.supportSASLMechanism("PLAIN", 0);
connection.connect();
Log.e("LOGIN", "" + 111);
// You have to put this code before you login
Log.e("LOGIN", "" + 222);
// You have to specify your gmail addres WITH #gmail.com at the end
connection.login("nemodo", "123456", "resource");
Log.e("LOGIN", "" + 333);
// See if you are authenticated
System.out.println(connection.isAuthenticated());
} catch (XMPPException e1) {
e1.printStackTrace();
}
I also get this mistake, but i can not work.
For anyone looking for possible solutions to this many years after this was originally asked and answered, I recently was able to get past this authentication error by explicitly setting the authzid value on the XMPPTCPConnectionConfiguration.
I was running into an issue where my connection configuration worked fine for some client XMPP servers, but not for others, even though they were all using SASL PLAIN authentication. After some troubleshooting, I learned that the ones that were failing were expecting an authzid value. After adjusting my code to set this, it works in both the environments that were working before, as well as the environments that were failing.
Here is how I am building my connection configuration:
XMPPTCPConnectionConfiguration.builder()
.setHost(XMPP_DOMAIN)
.setXmppDomain(XMPP_DOMAIN)
.setPort(XMPP_PORT)
.setCompressionEnabled(true) // optional, not all servers will support this
.setUsernameAndPassword(XMPP_USER, XMPP_PASSWORD)
.setResource(XMPP_RESOURCE)
.setAuthzid(JidCreate.entityBareFrom(String.format("%s#%s", XMPP_USER, XMPP_DOMAIN))) // <-- this was the change I needed
.build();
Specifically I needed to add this line:
.setAuthzid(JidCreate.entityBareFrom(String.format("%s#%s", XMPP_USER, XMPP_DOMAIN)))