How to consume Oauth2.0 REST API into ASP.NET Core MVC
Please send me some full project code if this is posibble
Thank you
How to consume Oauth2.0 REST API into ASP.NET Core MVC
Please send me some full project code if this is posibble
Thank you
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 15, 2024, 11:51 AM EST
Program.cs
using Microsoft.Identity.Client; var builder = WebApplication.CreateBuilder(args); // ... other configurations builder.Services.AddAuthentication(Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd")); builder.Services.AddAuthorization(); var app = builder.Build(); // ... other configurations app.UseAuthentication(); app.UseAuthorization();appsettings.json (this is just an example use any key-pair as per your API)
{ "AzureAd": { "Instance": "https://login.microsoftonline.com/", "Domain": "yourtenant.onmicrosoft.com", "ClientId": "your-client-id", "ClientSecret": "your-client-secret", "TenantId": "your-tenant-id", "CallbackPath": "/signin-oidc" } }public class YourController : Controller { private readonly IConfidentialClientApplication _confidentialClientApp; private readonly IHttpClientFactory _httpClientFactory; public YourController(IConfidentialClientApplication confidentialClientApp, IHttpClientFactory httpClientFactory) { _confidentialClientApp = confidentialClientApp; _httpClientFactory = httpClientFactory; } public async Task Index() { var result = await _confidentialClientApp.AcquireTokenForClient(new[] { "your-api-scope" }) .ExecuteAsync(); var accessToken = result.AccessToken; using var client = _httpClientFactory.CreateClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); // Make your API request using client // Example: var response = await client.GetAsync("https://api.example.com/data"); // Process the response return View(); } }Jignesh KumarRank #91 · 22.9K reputationPosted Jan 16, 2024, 12:43 AM EST
Hello Manish,
Please find below links that will help you out.
https://www.c-sharpcorner.com/article/asp-net-mvc-oauth-2-0-rest-web-api-authorization-using-database-first-approach/
https://www.c-sharpcorner.com/UploadFile/8a67c0/database-first-approach-with-Asp-Net-mvc-step-by-step-part-1/