I am trying to find the access token from AAD after user is authenticated from OpenId Connect. It is a web application integrated with AAD OpenId Connect. I need to get the access token to call another API that uses the same AAD. Here's what I've tried:
- Clone this sample code.
In Startup.cs file, add the following block of code:
public void ConfigureServices(IServiceCollection services) { services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor(); services.AddAuthentication(sharedOptions => { sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) .AddAzureAd(options => Configuration.Bind("AzureAd", options)) .AddOpenIdConnect("oidc", options => { options.Authority = "http://localhost:5000"; options.ClientId = "<<client-id>>"; options.SignInScheme = "cookie"; options.SaveTokens = true; options.GetClaimsFromUserInfoEndpoint = true; options.RequireHttpsMetadata = false; }) .AddCookie(); services.AddMvc();}
In
HomeController
class, I added a private variable calledhttpContextAccessor
and also set it in the constructor.private IHttpContextAccessor _httpContextAccessor; public HomeController(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; }
In the
HomeController
class, I added some code to access the access token.public IActionResult Index() { if (User.Identity.IsAuthenticated) { var attempt1 = Request.Headers["Authorization"]; var attempt2 = HttpContext.GetTokenAsync("access_token"); var attempt3 = _httpContextAccessor.HttpContext.GetTokenAsync("access_token"); var attempt4 = _httpContextAccessor.HttpContext.Request.Headers["Authorziation"]; } return View(); }
But all of them return either empty or null. Did I miss anything?
I've looked at this following posts for reference: How to refresh access token How to get access token from HttpContext in .Net core 2.0