Click here to Skip to main content
15,884,986 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
A token indicates which client_id is performing the API call. This token is retrieved using Authentication
Service by supplying client_id and API password as follow:
POST /connect/token HTTP/1.1
Host:www.xxxxxx.com
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials&client_id=<client_id>&client_secret=<client_secret>

Response
JavaScript
{
 "token_type": "Bearer",
 "access_token":"<access_token>",
 "expires_in": 3600
}

How to take that token from C# WinForms button Click?

What I have tried:

C#
private void SubmitBTN_Click(object sender, EventArgs e)
{
	var client = new RestClient($"https://dummy/api/");
	var request = new RestRequest("Create", Method.POST);
	request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
	request.AddParameter("grant_type", "client_credentials");
	request.AddParameter("client_id", "J<client_id>");
	request.AddParameter("client_secret", "<client_secret>");

	var response = client.Execute(request);
	if (response.StatusCode == System.Net.HttpStatusCode.OK)
	{
		string message = "OK";
		MessageBox.Show(message);
	}
	else
	{
		string message = "Error";
		MessageBox.Show(message);
	}
}
Posted
Updated 30-Oct-22 20:41pm
v3
Comments
Graeme_Grant 31-Oct-22 2:34am    
I have formatted your code for you.

I have also removed your API credentials as they are secret and should never be posted publicly. That is like posting your credit card and pin number publicly, you don't do it.

I highly recommend that you cancel your old credentials and get new ones.

1 solution

This is a Json response. You need to use a Json deserializer like Newtonsoft.Json or System.Text.Json APIs.

If you are using framework 4.8 or older, or DotNetCore 2.1 or older, then you need to use Newtonsoft.Json. If you are using DotNetCore 3.0, or newer, then System.Text.Json APIs are highly recommended.

If you are not familiar with either of these APIs, then please refer to one or both of these articles for more information:
1. Working with Newtonsoft.Json in C# & VB[^]
2. Working with System.Text.Json in C#[^]

The above articles were written to answer questions like yours, but to also answer most of your future questions as well.

Hope this helps!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900