Authorization header with HttpGet with proxy - http

I am using HttpGet with a proxy setting. The call works for endpoints that don't need an authorization token. For services that need a token, I use setHeader(), but see an error saying auth token missing.
What am I missing ?
HttpGet get = new HttpGet(endPoint);
get.setHeader("Authorization", token);
HttpHost proxy = new HttpHost("exampleproxy.com",8080);
RequestConfig config = RequestConfig.custom() .setProxy(proxy).build();
get.setConfig(config);
CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
CloseableHttpResponse response = httpclient.execute(get);
BufferedReader responseReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

Related

Pass FromHeader the httpClient to webapi 6.0

Below is the code, I have used to call the api. However, May I know how to pass http header
for example
Get customer has a header [FromHeader] field.
string uri = "https://localhost:7290/customers";
var response = await _httpClient.GetAsync(uri);
HttpClient GetAsync() is a shortcut for generating an instance of a HttpRequestMessage set to perform a GET for the specified URI and passing it to the SendAsync() method.
You can create your own request message instance and append additional details such as headers, then use the SendAsync() method yourself.
var request = new HttpRequestMessage(HttpMethod.Get, uri);
request.Headers.Add("header", "value");
var response = await client.SendAsync(request);
https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httprequestmessage?view=net-6.0

How to make a HTTP get call with request header in ASP.NET MVC to an API with Oauth2 authorization?

I'm having a hard time executing a http get call with headers to an api with oauth2 authorization.
I already tried the code below but then I'm receiving an Unauthorized response from the api. I think the problem is that because I've executed the GETASYNC() without the adding some headers. Can you help me to find a way on how to add headers before I execute the GETASYNC().
public HttpClient webApiClient = new HttpClient();
public async System.Threading.Tasks.Task<ActionResult> Index()
{
var uri = new Uri("https://myURL.com/"+ transno);
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var response = await webApiClient.GetAsync(uri);
response.Headers.Add("Accept", "application/json");
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response.Headers.Add("client-id", "clientid");
response.Headers.Add("client-secret", "clientsecret");
response.Headers.Add("partner-id", "partnerid");
var result = JObject.Parse(await response.Content.ReadAsStringAsync());
}

Implementing ROPC based authentication in asp .net core

I'm trying to implement ROPC flow in asp.net api . Can you please guide me on how to achieve this properly in ASP.net core using built in authentication library. If it is not possible what are the alternatives
I'm able to get the access token using http call to azure AD token endpoint. But i'm not able to validate the token using built in authentication library
can we implement this without the HTTP call , but using built in library.
services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
.AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
Im using the below code snippet to get the access token
private async Task<string> GetTokenAsync(string username, string password)
{
string grantType = "password";
string tenantId = Configuration["AzureAdNative:TenantId"];
string clientId = Configuration["AzureAdNative:ClientId"];
string resource = Configuration["AzureAdNative:Resource"];
string endpoint = "https://login.microsoftonline.com/" + tenantId + "/oauth2/token";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
var dict = new Dictionary<string, string>();
dict.Add("grant_type", grantType);
dict.Add("client_id", clientId);
dict.Add("username", username);
dict.Add("password", password);
dict.Add("resource", resource);
var req = new HttpRequestMessage(HttpMethod.Post, endpoint) { Content = new FormUrlEncodedContent(dict) };
var res = await client.SendAsync(req);
string result = res.Content.ReadAsStringAsync().Result;
var jwt = JObject.Parse(result);
return result;
// return jwt.GetValue("access_token").ToString();
}
getting unauthorised 401 error while validating with above code. access token is being sent in the authorization header (eg: Authorization : Bearer e4dgkddskdsdk).

Using RestSharp to request a URL with Windows authentication

I have a web site in IIS that its Authentication mode is set to Windows.
I need to call a URL in that site using restsharp :
var client = new RestClient(item.Url);
var request = new RestRequest("/account/Menu", Method.GET);
request.AddParameter("SSO_Token", token);
client.PreAuthenticate = false;
client.Authenticator = new RestSharp.Authenticators.NtlmAuthenticator(new NetworkCredential(username, password, domain));
// I also tried following codes with no luck:
// client.Authenticator = new RestSharp.Authenticators.NtlmAuthenticator();
// client.Authenticator = new RestSharp.Authenticators.NtlmAuthenticator(username, password);
var response = client.Execute(request);
now the problem is I get this error:
HTTP Error 401.1 - Unauthorized
You do not have permission to view this directory or page using the credentials that you supplied.
I'm sure the provided credential is correct.
This fixed it for me: https://www.codeproject.com/Questions/4043926/Why-is-my-API-throws-an-error-when-using-authentic
request.UseDefaultCredentials = true;

How to connect HTTPS in Win8 App with proxy

I can connect by http but can not connect https.
HttpRequestException Message:
An error occurred while sending the request.
System.Net.WebExceptionStatus.TrustFailure
HttpClientHandler clienthandler = new HttpClientHandler();
HttpClient client = new HttpClient(clienthandler);
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, "https://www.google.com.hk/");
req.Headers.Referrer = new Uri("https://www.google.com.hk/");
HttpResponseMessage mes = await client.SendAsync(req);

Resources