0

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:

  1. Clone this sample code.
  2. 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();}
    
  3. In HomeController class, I added a private variable called httpContextAccessor and also set it in the constructor.

        private IHttpContextAccessor _httpContextAccessor;
        public HomeController(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }
    
  4. 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

Nan Yu
  • 26,101
  • 9
  • 68
  • 148
superninja
  • 3,114
  • 7
  • 30
  • 63

1 Answers1

1

You need to set SaveTokens to true in OpenID Connect configuration:

  1. Clone that code sample
  2. Keep the Startup.cs , you don't need to add .AddOpenIdConnect part , AddAzureAd extension method would help add Azure Active Directory Authentication to your application.

  3. Modify the AzureAdAuthenticationBuilderExtensions.cs in Extensions folder :

    public void Configure(string name, OpenIdConnectOptions options)
    {
        options.ClientId = _azureOptions.ClientId;
        options.Authority = $"{_azureOptions.Instance}{_azureOptions.TenantId}";
        options.UseTokenLifetime = true;
        options.CallbackPath = _azureOptions.CallbackPath;
        options.RequireHttpsMetadata = false;
        options.SaveTokens = true;  // set to true 
    }
    
  4. Then you can get the ID token from httpContextAccessor:

    var idToken = _httpContextAccessor.HttpContext.GetTokenAsync("id_token");
    

But the access token is still null . The sample shows how to use the OpenID Connect ASP.NET Core middleware to sign-in users from a single Azure AD tenant , that means you can get the ID Token which is sent to the client application as part of an OpenID Connect flow and is used by the client to authenticate the user. Please refer to document : ID tokens .

While Access tokens enable clients to securely call APIs protected by Azure . Please refer to document : Azure Active Directory access tokens .

If you want to get the access token for accessing resource which protected by Azure AD , you should use ADAL(Azure AD V1.0 endpoint) to obtain the token , see code sample(especially use OnAuthorizationCodeReceived to acquire access token):

https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect-aspnetcore

Or use MSAL if you are using Azure AD V2.0 endpoint .

Nan Yu
  • 26,101
  • 9
  • 68
  • 148