Question

Difficulty: MediumMicrosoft Identity Platform Authentication

You are developing a secure C# web application that runs on-premises. The application must sign in users and then call a downstream Web API on their behalf using the Microsoft Identity Platform.

The application is configured as a confidential client. You have already obtained the authorization code from the initial user login redirect.

You write the following code to initialize the application:

csharp
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(clientSecret)
.WithRedirectUri(redirectUri)
.Build();

You need to complete the code to exchange the authorization code for an access token. Which code segment should you use?

  1. AuthenticationResult result = await app.AcquireTokenByAuthorizationCode(scopes, authorizationCode).ExecuteAsync();Answer
  2. B
    AuthenticationResult result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
  3. C
    AuthenticationResult result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault()).ExecuteAsync();
  4. D
    var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions { ManagedIdentityClientId = clientId });
    var tokenContext = new TokenRequestContext(scopes.ToArray());
    var token = await credential.GetTokenAsync(tokenContext);

Answer

AuthenticationResult result = await app.AcquireTokenByAuthorizationCode(scopes, authorizationCode).ExecuteAsync();
The application needs to exchange an authorization code for an access token to call a downstream API on behalf of a user. The app is a confidential client initialized as an IConfidentialClientApplication. The correct method to exchange the authorization code is AcquireTokenByAuthorizationCode, followed by ExecuteAsync to run the request.

Step-by-Step Solution

1
Identify the client type and the authentication flow needed.
The web application is a confidential client, and it must exchange an authorization code for a delegated user access token.
The scenario specifies a confidential client application that has already received an authorization code from a user login redirect.
2
Match the required flow to the correct MSAL.NET method.
Use the AcquireTokenByAuthorizationCode method of IConfidentialClientApplication.
This method is specifically designed to exchange the authorization code for access and refresh tokens.
3
Chain the MSAL builder execution method.
Append .ExecuteAsync() to the builder.
MSAL.NET uses a builder pattern, and .ExecuteAsync() must be called to send the asynchronous HTTP request to Microsoft Identity Platform.

Key Concept

Exchanging an authorization code for an access token using MSAL.NET ConfidentialClientApplication.
Rate this question