Not able to get certificate from HttpContext which was send from HttpClient - c#

Well, I tried many different solutions but none seems to be working.
I have created Self Signed Certificate from IIS Manager and also import this to cert store.(Current User\Personal\Certificates). I tried to send that cert using below code part:
var cert = new X509Certificate2(#"C:\\Test.pfx", "asdf");
var handler = new HttpClientHandler() { ClientCertificateOptions = ClientCertificateOption.Manual };
handler.ClientCertificates.Add(cert);
var client = new HttpClient(handler);
var request = new HttpRequestMessage()
{
RequestUri = new Uri("https://localhost:44351/helloworld"),
Method = HttpMethod.Get,
};
var response = client.SendAsync(request).GetAwaiter().GetResult();
if (response.IsSuccessStatusCode)
{
var responseContent = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
}
But I when tried to receive it, it consists of null.
var clientCertificate = httpContext.Connection.ClientCertificate;
I think there exist some underlying concepts which I am not able to find out.

Related

Send HTTP Request doesn't work with WebProxy

I'm scraping data from some sites and one of theses use headers for some information. I'm using Smart Proxy Manager from Zyte and having problems with a request with headers. When I use the zyte proxy, I receive a response, but the site that I'm scraping return an unsuccess message. If I not use the proxy, the request works like a charm. Can anyone help me?
Here is my code
string zyteKey = _configuration["ZyteKey"];
var proxy = new WebProxy("myproxy");
proxy.Credentials = new NetworkCredential(zyteKey, "");
var clientHandler = new HttpClientHandler()
{
Proxy = proxy,
UseProxy = true,
PreAuthenticate = true,
AllowAutoRedirect = false
};
using (var client = new HttpClient(clientHandler))
{
string json = JsonConvert.SerializeObject(jsonObject);
var content = new StringContent(json, Encoding.UTF8, "application/json");
client.Timeout = new TimeSpan(0, 1, 0);
client.DefaultRequestHeaders.Add("cookie", BuildCookieRequest(latitude, longitude, restaurantName));
client.DefaultRequestHeaders.Add("Accept", "application/json, text/plain, */*");
client.DefaultRequestHeaders.Add("x-csrf-token", "x");
return await client.PostAsync(url, content);
}

How to access key vault secret from .net code hosted on IIS

I have a Scenario:
Create Key vault with secret in Azure.
Access this secret in Code.
code is working in Local(tested using Azure CLI)
Application hosted in Azure App service(MSI enable) working fine.
We need to Host same application on Azure VM(MSI enable) IIS server-Not working
I want the solution and suggestions for above point(Last point)
Code to Access Key vault Secret value
var azureServiceTokenProvider = new AzureServiceTokenProvider();
var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
ConfigurationApp.ClientId = keyVaultClient.GetSecretAsync("https://test.vault.azure.net/", "testid").Result.Value;
Follow this Article -
https://kasunkodagoda.com/2018/04/28/allow-application-running-on-an-azure-virtual-machine-to-access-azure-key-vault-using-managed-service-identity/
https://azure.microsoft.com/en-us/resources/samples/app-service-msi-keyvault-dotnet/
I have fixed my issue:Access key vault secret from .net code hosted on Azure VM IIS
public async Task getAppconfiguration2()
{
string URI = "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fvault.azure.net";
Uri uri = new Uri(String.Format(URI));
HttpClient _client = new HttpClient();
_client.DefaultRequestHeaders.Add("Metadata", "true");
HttpRequestMessage request = new HttpRequestMessage
{
// Content = new StringContent(body, Encoding.UTF8, "application/json"),
Method = HttpMethod.Get,
RequestUri = new Uri(URI)
};
var res = await _client.SendAsync(request);
var content = res.Content.ReadAsStringAsync();
JObject token = JsonConvert.DeserializeObject<JObject>(content.Result.ToString());
string token1 = token["access_token"].ToString();
ConfigurationApp.Encyptionkey = token1.ToString();
HttpClient _client1 = new HttpClient();
_client1.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token1);
HttpRequestMessage request1 = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("https://test.vault.azure.net/secrets/clientid?api-version=2016-10-01")
};
var rs = _client1.SendAsync(request1);
var rk = rs.Result.Content.ReadAsStringAsync();
JObject clientjson = JsonConvert.DeserializeObject<JObject>(rk.Result.ToString());
ConfigurationApp.ClientId = clientjson["value"].ToString();
}

HttpRequestMessage is null in HttpClientHandler.ServerCertificateCustomValidationCallback

I am attempting to use the ServerCertificateCustomValidationCallback of HttpClientHandler but the value of the request parameter is always null. Is this expected behavior or do I need to set a bit somewhere?
For example the following snippet results in printing Request not defined 4 times.
var handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = (_request,_certificate, _chain,_errors) =>
{
Console.WriteLine(_request?.RequestUri.ToString() ?? "Request not defined");
return true;
};
var client = new HttpClient(handler);
var request = new HttpRequestMessage(HttpMethod.Get, "https://google.com");
client.SendAsync(request);
client.GetAsync("https://google.com");

HttpClient throws error with the Rest services

I am trying to call multiple rest services from the Web API I am creating and I am getting the below error while one of the Sharepoint rest service is called
This instance has already started one or more requests. Properties can only be modified before sending the first request.
Below is the code for calling the rest services using the HttpClient
try
{
var credential = new NetworkCredential(userName_SP, password_SP, domain_SP);
var myCache = new CredentialCache();
myCache.Add(new Uri(core_URL), "NTLM", credential);
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = true;
handler.Credentials = myCache;
using (var client_sharePoint = new HttpClient(handler))
{
var response = client_sharePoint.GetAsync(core_URL).Result;
client_sharePoint.BaseAddress = uri;
client_sharePoint.DefaultRequestHeaders.Accept.Clear();
client_sharePoint.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var responsedata = await response.Content.ReadAsStringAsync();
var returnObj = JsonConvert.DeserializeObject<SharepointDTO.RootObject>(
responsedata);
return returnObj;
}
...
I have never encountered this error before. Can anyone please suggest me if I need set the timeout
Try this:
var credential = new NetworkCredential(userName_SP, password_SP, domain_SP);
var myCache = new CredentialCache();
myCache.Add(new Uri(core_URL), "NTLM", credential);
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = true;
handler.Credentials = myCache;
using (var client_sharePoint = new HttpClient(handler))
{
client_sharePoint.BaseAddress = uri;
client_sharePoint.DefaultRequestHeaders.Accept.Clear();
client_sharePoint.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client_sharePoint.GetAsync(core_URL);
var responsedata = await response.Content.ReadAsStringAsync();
var returnObj = JsonConvert.DeserializeObject<SharepointDTO.RootObject>(
responsedata);
return returnObj;
}
Headers and BaseAddress must be set before you make the request with GetAsync.
I also took the liberty to change from .Result to await since calling .Result is poor practice and I can see this is in an async method.
You should also read this: https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/

Windows 8.1 store app Download file using authentication and header

I'm trying to download a file from a server and adding authentication and range header in my app, so is this syntax correct?
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
request.Headers["Range"] = "bytes=0-";
request.Credentials = new NetworkCredential("username","password");
Of course the code has other parts for reading the file as a stream and storing it but i'm concerned with the range header and authentication part because it's not working.
I get an exception
{"The 'Range' header must be modified using the appropriate property or method.\r\nParameter name: name"}
Here's how to do it:
public async Task<byte[]> DownloadFileAsync(string requestUri)
{
// Service URL
string serviceURL = "http://www.example.com";
// Http Client Handler and Credentials
HttpClientHandler httpClientHandler = new HttpClientHandler();
httpClientHandler.Credentials = new NetworkCredential(username, passwd, domain);
// Initialize Client
HttpClient client = new HttpClient(httpClientHandler)
client.BaseAddress = new Uri(serviceURL);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson"));
// Add Range Header
client.DefaultRequestHeaders.Add("Range", "bytes=0-");
// Deserialize
MemoryStream result = new MemoryStream();
Stream stream = await client.GetStreamAsync(requestUri);
await stream.CopyToAsync(result);
result.Seek(0, SeekOrigin.Begin);
// Bson Reader
byte[] output = null;
using (BsonReader reader = new BsonReader(result))
{
var jsonSerializer = new JsonSerializer();
output = jsonSerializer.Deserialize<byte[]>(reader);
}
return output;
}
I'm current using the BSON media format. If you need addtional information regarding BSON in your backend, herre's a great article on how to implement it and consume it:
http://www.strathweb.com/2012/07/bson-binary-json-and-how-your-web-api-can-be-even-faster/
Here is another way to do it
var httpClientHandler = new HttpClientHandler();
httpClientHandler.Credentials = new System.Net.NetworkCredential("username", "password");
var client = new HttpClient(httpClientHandler);
System.Net.Http.HttpRequestMessage request = new System.Net.Http.HttpRequestMessage(HttpMethod.Post, new Uri(url));
request.Headers.Range = new RangeHeaderValue(0, null);
HttpResponseMessage response = await client.SendAsync(request);

Categories

Resources