Migrating From HttpClientv4 to v.5 - http

We are trying to migrate our project from http v.5 to v.5 and facing an issue. tried alot but nothing is working as of now.
Old Code.
private CloseableHttpClient httpClient;
httpClient = HttpClients.custom().setSSLSocketFactory(new SSLConnectionSocketFactory(SSLContext.getDefault(),
supportedProtocols,supportedCipherSuites,
HttpsURLConnection.getDefaultHostnameVerifier())).setSSLHostnameVerifier
(HttpsURLConnection.getDefaultHostnameVerifier())
.build();
What will be the possible replacement.

Related

How to get client page URI for a given SignalR .Net Core Connection

I am upgrading my ASP.Net MVC Application to ASP.Net Core 3.1
In the existing app I am able to get to the URL that the SignalR connection is coming from by overriding the OnConnected method of the Hub class, and reading Context.Headers("referer"). I would use this to be able to tell on which page of my app each SignalR connection is.
However, in SignalR .Net Core, there is no such header sent.
How can I get to the referring URL for the SignalR connections in .Net Core 3.1?
How can I get to the referring URL for the SignalR connections in .Net Core 3.1?
To achieve your requirement, you can try to pass the path and filename of the current page as query string while you configure the HubConnection, like below.
var pn = window.location.pathname;
var connection = new signalR.HubConnectionBuilder().withUrl("https://xxxx/chatHub?pagename=" + pn)
.build();
Then on your hub server, you can get them using following code snippet.
public override async Task OnConnectedAsync()
{
var httpcontext = Context.GetHttpContext();
var pname = httpcontext.Request.Query["pagename"];
var from = httpcontext.Request.Headers["Origin"];
//code logic here
await base.OnConnectedAsync();
}
Test Result

Poor Azure App Service performance using OWIN?

We recently deployed a .NET Framework 4.8 Web API 2 application to an Azure App Service. We’re using the Azure S1 application service plan.
Unfortunately, we’re seeing very inconsistent response times when making API requests to this service – sometimes as long as 10 seconds. The same application running on a VM takes less than a second.
Initially we assumed it was slow database query performance, but after doing some profiling it appears the queries actually run quickly and most of the time appears to be in “external code”.
Specifically, it appears that most of the time is spent in the OWIN request handler code:
Here is our Startup.cs:
app.UseCors(CorsOptions.AllowAll);
app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions() {
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(AccessTokenExpirationInMinutes),
Provider = new CustomOAuthAuthorizationProvider()
});
app.UseCustomSessionAuthentication(new CustomSessionAuthenticationOptions());
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
var config = GlobalConfiguration.Configuration;
WebApiConfig.Register(config);
ServiceConfig.Register(config);
app.UseWebApi(config);
Has anyone experienced issues using OWIN in an Azure App Service? Is there special configuration or code changes needed?
Versions:
.NET Framework 4.8
MVC 5.2.3
Microsoft.Owin.* 3.0.1

HttpClient.GetAsync works with LocalHost API, but not Live API

I have a .Net 4.5.2 WebApp that is calling my API. When I point my web app to the LocalHost version of my API, it gets the data, and comes back just fine. I published that API, and confirm that the API is working correctly with PostMan.
Then I run the exact same WebApp code, changing only the URI from localhost to live api, and I get a multiple exception error consisting of the following:
An existing connection was forcibly closed by the remote host
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
The underlying connection was closed: An unexpected error occurred on a send.
An error occurred while sending the request.
Here's my calling code
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("user", serializedUser);
response = null;
try
{
//Uri uri = new Uri("https://jsonplaceholder.typicode.com/posts/1");//https works
Uri uri = new Uri("https://api.acme.com/values/test");
//Uri uri = new Uri("http://localhost/5000/values/test"); //http localhost works
response = client.GetAsync(uri).Result;
}
catch (Exception e)
{
string er = e.Message;
}
}
EDIT 1: I created a .NET Core app from scratch, and my original code works perfectly calling my live API. My original code also work in .NET 4.5.2 calling a different "https" API.
EDIT 2:
So this is where I'm at now, I have created two generic apps from VS 2015, one is a .NET Core Web App, the other a .NET Framework Web App. I have used the above code exactly the same in both apps to call the API. In both apps, I can call a generic "https" api I found online (jsonplaceholder). I can also call the localhost version of my app at "http" from both. In the .NET Core version of the app, I can call my "https" live API and get the results I'm looking for. In the .NET Framework app I still get the same errors.
I can't figure out what the difference is between my Core and Framework requests that is getting one shut down when the other isn't.
It seems you are hosting the application on secured http environment (https). Are you using SSL certificate on the server where you are hosting your Web API? If not, It might be throwing the certificate related exceptions.
Just add the following line before the call to GetAsync and This will ignore the SSL errors.
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
This is only recommended in an intranet environment or other closed network where server identities can't be forged.
C# Ignore certificate errors?
Adding the following line before my API call fixed the issue, but I'd love to hear an explanation of what this line does, and any security risks this might impose using it in my web app.
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
Props to this answer!

An API service I use is disabling SSL 3.0 because of the POODLE exploit. If I use HttpClient and HttpRequestMessage do I need to change my code?

Say I do typical stuff like this:
HttpRequestMessage requestMessage = new HttpRequestMessage();
requestMessage.RequestUri = new Uri("https://api.site.com/");
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Task<HttpResponseMessage> responseMessage = httpClient.SendAsync(requestMessage);
And the API service tells me they're turning off SSL 3.0 because of the POODLE exploit, do I have to do anything to my code to make sure it will use TLS? Does anything need to happen with the machine making the request?
I'm aware that there's a significant amount of ignorance baked into the question, but I think a lot of developers just want this question answered.
I faced same issue for Facebook and twitter yesterday and Linkedin from today. Added the following piece of code before every web request worked for me.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
It was lot confusing as on restarting the application, it worked for 10-15 mins before the first error. Following was the error logged.
System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.
I tried powershell script to disable ssl and enable tls in the server using http://www.hass.de/content/setup-your-iis-ssl-perfect-forward-secrecy-and-tls-12
It did not work and finally had to change the code to make it work.

Get AngularJS to talk to .NET Web API secured with Azure AD

I have two different web projects on Microsoft Azure. One project is a .NET MVC web application and the other project is a .NET Web API.
Both projects are configured to use Azure AD. The MVC web application is able to get a token and use it to make requests against the Web API. Here's sample code from the MVC web app.
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, new NaiveSessionCache(userObjectID));
ClientCredential credential = new ClientCredential(clientId, appKey);
result = authContext.AcquireTokenSilent(todoListResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
// Make a call against the Web Api
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, webApiBaseAddress + "/api/list");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = await client.SendAsync(request);
So this code works just fine. However, what I need to do now is call the Web API directly from an AngularJS application. When I try to do that, I get a 401 unauthorized error.
The way I am doing this is by adding a header to the HTTP GET request sent by AngularJS. I'm setting "Bearer" to the result.AccessToken value that I am passing to the page from my MVC application (code above).
Obviously this doesn't work. I suppose now my question is what are my options? Is there an official or better way to do this? Let's say I wanted to make calls to the Web API from standard JavaScript (lets forget the complexities of AngularJS). Is there a way to authenticate with Azure AD?
the canonical way of obtaining a token for an in-browser JS application would be to use the OAuth2 implicit flow. Azure AD does not currently expose that flow, but stay tuned: we are working on enabling the scenario. No dates to share yet.
HTH!
V.
The work I mentioned in the older answer finally hit the preview stage. Please take a look at http://www.cloudidentity.com/blog/2014/10/28/adal-javascript-and-angularjs-deep-dive/ - that should solve precisely the scenario you described. If you have feedback on the library please do let us know!
Thanks
V.

Resources