Api calling in .net core razor pages - asp.net-core

I am working on (built-in web apis) provided by whatsapp business api. As a newbie in .net core razor pages and web apis. I want to know how can I get access to the body of the post request api. Take an example below for sending a message
Post: {URL}/v1/messages
Request Body:
"to": "",
"message_type:"
"message_text:"
"recipient_type: "individual | group""
How can I make a call to the builtin api and access the body parts of it?
Ofcourse, we as a developer can use postman for checking the working of api. But take this as a client and for the client we have some fields like
To:
Message:
How can take these fields and put it into the api call body and then when the user click on the send, the api call works and shows whatever we want to show the user for example a model with send successfully etc.

You can call the API using HttpClient.
Add the URL in await client.PostAsync() function. If you have authorization use client.DefaultRequestHeaders.Authorization otherwise omit it
string myContent = "";
string myJson = <JsonQuery>;
using (HttpClient client = new HttpClient())
{
// If any authorization available
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenLabel.Text.Trim());
using (HttpResponseMessage response = await client.PostAsync("https:url", new StringContent(myJson, Encoding.UTF8, "application/json")))
{
using (HttpContent content = response.Content)
{
myContent = await content.ReadAsStringAsync();
}
}
}
Update
Content
string myJson = "{\"subject\": }";
URL
using (HttpResponseMessage response = await client.PostAsync("{{URL}}/v1/groups", new StringContent(myJson, Encoding.UTF8, "application/json")))
Header
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "");

Related

C# HttpClient failing to make GET requests with Windows Authentication

I have a .NET Core 3.1 Api application with the following configuration of HttpClient. In Startup.cs
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddHttpClient("myapi", c =>
{
c.BaseAddress = new Uri(Configuration["endpoint"]);
c.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
IISDefaults.AuthenticationScheme, Convert.ToBase64String(
System.Text.Encoding.UTF8.GetBytes($"{Configuration["username"]}:{Configuration["password"]}")));
});
I then try to make an HTTP call like this:
var client = clientFactory.CreateClient(clientName);
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
return await response.Content.ReadAsStringAsync();
however I always get an Unauthorized response when calling an internal api. Under Debug I have Windows authentication and Anonymous authentication both enabled.
With Postman my api calls go through, which verifies that I got the right credentials.
Can you suggest any alterations to make this work?
Instead of c.DefaultRequestHeaders.Authorization =, I'm having config like this
c.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
Credentials = new NetworkCredential("username", "password"),
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
PreAuthenticate = true
});
I guess this will not work as-is in your case, but I hope this can get you on track.

Using httpClient.postasync for web api calls .netcore

I am new to .netcore, I am working on web api that are running on docker container and while using postman the web api's are working really fine outputting the results. I want to make a program in .netcore calling the webapi endpoints and getting the response and using that particular response in other endpoints with MVC.
The explanation is given below.
The default username and password for admin is default set for example username:admin , password: helloworld
. The first time admin login the api requires a new personal password as shown in the Postman figure below.
The login api is: localhost://..../v1/users/login
The first question is How to give the values in Authorization->BasicAuth using .netcore.
The body of the api looks like the figure below.
After setting the new_password the response of the api is a token as given below.
The particular token is then use in the Environment to create user. The image for more clear problem is given below.
Lastly, the token then used to make other API calls such as creating a user.
API: https://localhost/..../v1/users
The image is below.
As a newbie in .netcore language, I am really struggling to do this kind of API calls, as most of the tutorials I tried are generating their own token from API, but here I just want to take the response token and save it and then use it in other API calls.
The StackOverflow community's support was always really handy for me.
The Code I'm trying is given below.
**Controller**
public class Login_AdminController : ControllerBase
{
[Route("/loginAdmin")]
[HttpPost]
public async Task<string> LoginAdminAsync([FromBody] dynamic content)
{
LoginAdmin L = new LoginAdmin();
var client = new HttpClient();
client.BaseAddress = new Uri("https://localhost:9090");
var request = new HttpRequestMessage(HttpMethod.Post, "/v1/users/login");
var byteArray = new UTF8Encoding().GetBytes($"<{L.username}:{L.df_Password}>");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var formData = new List<KeyValuePair<string, string>>();
formData.Add(new KeyValuePair<string, string>("new_password", "helloWorld123!"));
request.Content = new FormUrlEncodedContent(formData);
var response = await client.SendAsync(request);
Console.WriteLine(response);
return content;
}
}
}
***Model***
public class LoginAdmin
{
public string username = "admin";
public string df_Password = "secret";
public string new_Password { get; set; }
}
Thank you.
Do you want to get token from response? If yes. Try this:
var client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:12345/Api");
var request = new HttpRequestMessage(HttpMethod.Post, "/token");
var keyValues = new List<KeyValuePair<string, string>>();
keyValues.Add(new KeyValuePair<string, string>("username", "yourusername"));
keyValues.Add(new KeyValuePair<string, string>("password", "yourpassword"));
request.Content = new FormUrlEncodedContent(keyValues);
var response = client.SendAsync(request).Result;
return response.Content.ReadAsStringAsync().Result;
Authorization is handled via the Authorization request header, which will include a token of some sort, prefixed by the scheme. What you're talking about here isn't really basic auth. With that, you literally pass the username and pass in the Authorization header with each request. What you're doing is just authenticating once to get an auth token, and then using that auth token to authorize further requests. In that scenario, you should really be posting the username and pass in the request body. Then, you'd do bearer auth with the token for the other requests, using the Authorization header. Still, to cover both bases:
Basic Auth
var token = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}"));
request.Headers.Add("Authorization", $"Basic {token}");
Bearer Auth
request.Headers.Add("Authorization", $"Bearer {token}");
// where `token` is what was returned from your auth endpoint
FWIW, List<KeyValuePair<string, string>> is just Dictionary<string, string>. It's better to use the real type. Then, you can just do formData.Add("new_password", "helloWorld123!") instead of formData.Add(new KeyValuePair<string, string>("new_password", "helloWorld123!"))

.NET Core 2 programmatically authentcation on Keycloak example

I'm trying to authenticate through a device (it's a barcode reader) that use .NET Core. I'm a newbie on .NET Core.
Now I need to write some program that gives me the possibility that given a username/password I make authentication on a Keycloak server with openidconnect. Is there some sample that shows how from a username/password string I can make the authentication programmatically?
I find a lot of examples that use .NET Core as a server that has Controllers that exposes rest API for user that have to be authenticated. But I need some example/hint to follow where the .NET Core makes the request.
Update
I could figure out (with curl) what exactly I have to do. Two calls to the Keycloak server.
call:
http://keycloakserver/auth/realms/realmName/protocol/openid-connect/token?grant_type=password&client_id=demo-app&username=username&password=password
This gives me back an object containing the access_token.
invoke the secured service adding in the header
"Authorization: bearer +access_token"
I try to develop this two calls with .NET Core.
I found this way to resolve it. But I'm sure is not the best way. I think there is a lot of improvement of security:
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/vnd.github.v3+json"));
client.DefaultRequestHeaders.Add("User-Agent", ".NET Foundation Repository Reporter");
var values = new Dictionary<string, string>
{
{ "client_id", "myClientId" },
{ "grant_type", "password" },
{ "username", "usernaName" },
{ "password", "password" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://domain/auth/realms/realmName/protocol/openid-connect/token", content);
var responseString = await response.Content.ReadAsStringAsync();
var responseToken = JsonConvert.DeserializeObject<ResponseToken>(responseString);
Console.WriteLine("accessToken: " + responseToken.AccessToken);
var client2 = new HttpClient();
client2.DefaultRequestHeaders.Accept.Clear();
client2.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/vnd.github.v3+json"));
client2.DefaultRequestHeaders.Add("User-Agent", ".NET Foundation Repository Reporter");
client2.DefaultRequestHeaders.Add("Authorization", "bearer "+ responseToken.AccessToken);
var dataResponse = client2.GetStreamAsync("http://serviceDomain/api/SampleData/WeatherForecasts");
var serializer = new DataContractJsonSerializer(typeof(List<Weather>));
var tempData = serializer.ReadObject(await dataResponse) as List<Weather>;
Console.WriteLine(tempData);
If you have a better solution then don't hesitate to post it.

Sharepoint 2013 REST api from desktop application - Authentication

I am trying to consume SharePoint 2013 REST services from a Desktop application ( cross-platform, cross-os ). Application is basically a HTML page in application view.
Is there a simple way I can authenticate my calls using HTTP methods ?
Yes, you can get authenticated and receive a digest via a REST call.
string url = "http://Your.SP.Site";
HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
client.BaseAddress = new System.Uri(url);
string cmd = "_api/contextinfo";
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("ContentType", "application/json");
client.DefaultRequestHeaders.Add("ContentLength", "0");
StringContent httpContent = new StringContent("");
var response = client.PostAsync(cmd, httpContent).Result;
if (response.IsSuccessStatusCode)
{
string content = response.Content.ReadAsStringAsync().Result;
JsonObject val = JsonValue.Parse(content).GetObject();
JsonObject d = val.GetNamedObject("d");
JsonObject wi = d.GetNamedObject("GetContextWebInformation");
retVal = wi.GetNamedString("FormDigestValue");
}
The above example shows how to retrieve the digest in C# with the HttpClient. This string needs to be passed as a header to all of the other rest calls you make to carry forward the authentication. You can create a credential by passing in a username and password if needed.
I have more examples here:
https://arcandotnet.wordpress.com/2015/04/01/sharepoint-2013-rest-services-using-c-and-the-httpclient-for-windows-store-apps/
You can do these calls in JavaScript as well and Microsoft has a lot of documentation on that. There is also .NET library, Microsoft.SharePoint.Client.DLL (CSOM) that simplifies this type of coding but you must have the library installed on the client.

How to call API URL windows 8 C#

I am new to windows 8. I want to call api url and the response will be return in terms of json. My Question is how to call below api url in my windows 8 code with c#.
API URL: http://scwin8dashboard.cloudapp.net/shell/~/analytics/reports/reports.ashx?fff=0&report=CampaignCategoriesOverview&languages=&sites=&startDate=20080101&endDate=20121114&addLastModified=true
please help
var uri = "http://scwin8dashboard.cloudapp.net/shell/~/analytics/reports/reports.ashx?fff=0&report=CampaignCategoriesOverview&languages=&sites=&startDate=20080101&endDate=20121114&addLastModified=true";
var client = new HttpClient();
var response = await client.GetStringAsync(uri);
var parser = JsonObject.Parse(response);
For more informations about Http requests see this page.
For JSON related classes see the Windows.Data.Json namespace.