Code to call external api with OAuth 2.0 authentication
Loading
Code to call external api with OAuth 2.0 authentication
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Sachin SinghRank #66 · 26.2K reputationPosted Jan 8, 2024, 3:28 AM EST
You can use this
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; class Program { static async Task Main() { // Replace these values with your actual OAuth 2.0 credentials string clientId = "your_client_id"; string clientSecret = "your_client_secret"; string accessToken = await GetAccessToken(clientId, clientSecret); if (!string.IsNullOrEmpty(accessToken)) { // Replace this URL with the API endpoint you want to call string apiUrl = "https://api.example.com/resource"; // Make the API request using the access token await CallApi(apiUrl, accessToken); } Console.ReadLine(); } static async Task GetAccessToken(string clientId, string clientSecret) { // Replace these values with the OAuth 2.0 token endpoint and required parameters string tokenEndpoint = "https://oauth.example.com/token"; string scope = "your_api_scope"; using (HttpClient client = new HttpClient()) { // Set the required headers for token endpoint authentication client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"{clientId}:{clientSecret}"))); // Set the parameters for token request var content = new FormUrlEncodedContent(new[] { new KeyValuePair("grant_type", "client_credentials"), new KeyValuePair("scope", scope) }); // Call the token endpoint to get the access token HttpResponseMessage response = await client.PostAsync(tokenEndpoint, content); if (response.IsSuccessStatusCode) { var responseContent = await response.Content.ReadAsStringAsync(); // Parse the JSON response to get the access token // Note: You may need to use a JSON parsing library here // For simplicity, we are assuming a simple JSON response format // Make sure to handle errors and parse the response appropriately in a production scenario return responseContent.Split('"')[3]; } else { Console.WriteLine($"Error getting access token: {response.StatusCode}"); return null; } } } static async Task CallApi(string apiUrl, string accessToken) { using (HttpClient client = new HttpClient()) { // Set the access token in the Authorization header client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); // Make the API request HttpResponseMessage response = await client.GetAsync(apiUrl); if (response.IsSuccessStatusCode) { string apiResponse = await response.Content.ReadAsStringAsync(); Console.WriteLine($"API Response: {apiResponse}"); } else { Console.WriteLine($"Error calling API: {response.StatusCode}"); } } } }Satyaprakash SamantarayRank #101 · 21.1K reputationPosted Jan 8, 2024, 3:13 AM EST
Hi,
Please check
http://tinyurl.com/yjyetf5z
Anandu G NathRank #681 · 3.5K reputationPosted Jan 8, 2024, 5:30 AM EST
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace OAuth2APICallExample { class Program { static async Task Main(string[] args) { string apiUrl = "YOUR_API_ENDPOINT"; // Replace with your API endpoint string accessToken = "YOUR_ACCESS_TOKEN"; // Replace with your OAuth 2.0 access token using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); HttpResponseMessage response = await client.GetAsync(apiUrl); if (response.IsSuccessStatusCode) { string responseData = await response.Content.ReadAsStringAsync(); Console.WriteLine("API call successful. Response:"); Console.WriteLine(responseData); } else { Console.WriteLine($"Failed to call API. Status code: {response.StatusCode}"); } } } } }Meghana M Check this code