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?
- AuthenticationResult result = await app.AcquireTokenByAuthorizationCode(scopes, authorizationCode).ExecuteAsync();Answer
- BAuthenticationResult result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
- CAuthenticationResult result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault()).ExecuteAsync();
- Dvar 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
Key Concept
Exchanging an authorization code for an access token using MSAL.NET ConfidentialClientApplication.