2
votes

I have configured Open ID Connect with Azure AD. I wish to retrieve the access_token from AAD. Currently I am only able to retrieve the id_token. I have configured my Azure Active Directory App registration to include both the access_token and the id_token.

I have configured my Azure Active Directory App registration to include both the access_token and the id_token. I have also tried retrieving the token from the header without any luck.

Startup.cs

services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
                .AddAzureAD(options => Configuration.Bind("AzureAD", options));
            services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
            {
                options.Authority = options.Authority + "/v2.0/";
                options.TokenValidationParameters.ValidateIssuer = true;
                options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
                options.SaveTokens = true;
            });

MyController.cs

if(User.Identity.IsAuthenticated)
            {
                string accessToken = await HttpContext.GetTokenAsync("access_token");
                string idToken = await HttpContext.GetTokenAsync("id_token");
}

appsettings.json

"AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "mydomain",
    "TenantId": "organizations",
    "ClientId": "myclientid",
    "ClientSecret": "myclientsecret",
    "CallbackPath": "/signin-oidc",
    "SignedOutCallbackPath ": "/signout-callback-oidc"
  }
2
You can use MSAL to get the tokens in this case. With OIDC, you need to exchange the code for the tokens after authentication. There is a callback you can setup, where you can use MSAL to get tokens and get them stored in token cache. Then in other parts you can use the silent variants of AcquireToken to get cached/refreshed tokens. - juunas

2 Answers

1
votes

You will need to use CodeIdTokenToken response type, according to the documentation

options.ResponseType = OpenIdConnectResponseType.CodeIdTokenToken;

0
votes

I managed to fix this. To anyone that would encounter this issue, set the response type to Code to get both the id_token and the access_token. This will instruct Open ID Connect to use the authorization code flow.

options.ResponseType = OpenIdConnectResponseType.Code