Skip to content
This repository was archived by the owner on Nov 16, 2023. It is now read-only.

Commit 8415b74

Browse files
committed
Updating the README.md
1 parent f685219 commit 8415b74

File tree

1 file changed

+32
-13
lines changed

1 file changed

+32
-13
lines changed

README.md

Lines changed: 32 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -166,37 +166,56 @@ This sample shows how to use MSAL to redeem the authorization code into an acces
166166
The redemption takes place in the `AuthorizationCodeReceived` notification of the authorization middleware. Here there's the relevant code:
167167

168168
```csharp
169+
// Use MSAL to swap the code for an access token
170+
// Extract the code from the response notification
169171
var code = context.ProtocolMessage.Code;
170-
string signedInUserID = context.Ticket.Principal.FindFirst(ClaimTypes.NameIdentifier).Value;
171-
TokenCache userTokenCache = new MSALSessionCache(signedInUserID, context.HttpContext).GetMsalCacheInstance();
172172

173-
ConfidentialClientApplication cca = new ConfidentialClientApplication(AzureAdB2COptions.ClientId, AzureAdB2COptions.Authority, AzureAdB2COptions.RedirectUri, new ClientCredential(AzureAdB2COptions.ClientSecret), userTokenCache, null);
173+
string signedInUserID = context.Principal.FindFirst(ClaimTypes.NameIdentifier).Value;
174+
IConfidentialClientApplication cca = ConfidentialClientApplicationBuilder.Create(AzureAdB2COptions.ClientId)
175+
.WithB2CAuthority(AzureAdB2COptions.Authority)
176+
.WithRedirectUri(AzureAdB2COptions.RedirectUri)
177+
.WithClientSecret(AzureAdB2COptions.ClientSecret)
178+
.Build();
179+
new MSALStaticCache(signedInUserID, context.HttpContext).EnablePersistence(cca.UserTokenCache);
174180

175181
try
176182
{
177-
AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, AzureAdB2COptions.ApiScopes.Split(' '));
178-
context.HandleCodeRedemption(result.AccessToken, result.IdToken);
183+
AuthenticationResult result = await cca.AcquireTokenByAuthorizationCode(AzureAdB2COptions.ApiScopes.Split(' '), code)
184+
.ExecuteAsync();
185+
186+
187+
context.HandleCodeRedemption(result.AccessToken, result.IdToken);
188+
}
179189
```
180190

181191
Important things to notice:
182-
- The `ConfidentialClientApplication` is the primitive that MSAL uses to model the application. As such, it is initialized with the main application's coordinates.
183-
- `MSALSessionCache` is a sample implementation of a custom MSAL token cache, which saves tokens in the current HTTP session. In a real-life application, you would likely want to save tokens in a long lived store instead, so that you don't need to retrieve new ones more often than necessary.
184-
- The scope requested by `AcquireTokenByAuthorizationCodeAsync` is just the one required for invoking the API targeted by the application as part of its essential features. We'll see later that the app allows for extra scopes, but you can ignore those at this point.
192+
- The `IConfidentialClientApplication` is the interface that MSAL uses to model the application. As such, it is initialized with the main application's coordinates.
193+
- `MSALStaticCache` is a sample implementation of a custom MSAL token cache, which saves tokens in memory. In a real-life application, you would likely want to save tokens in a long lived store instead, so that you don't need to retrieve new ones more often than necessary. For examples of such caches see [ASP.NET Core Web app tutorial | Token caches](https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/tree/master/2-WebApp-graph-user/2-2-TokenCache)
194+
- The scope requested by `AcquireTokenByAuthorizationCode` is just the one required for invoking the API targeted by the application as part of its essential features. We'll see later that the app allows for extra scopes, but you can ignore those at this point.
185195

186196
### Using access tokens in the app, handling token expiration
187197

188198
The `Api` action in the `HomeController` class demonstrates how to take advantage of MSAL for getting access to protected API easily and securely. Here there's the relevant code:
189199

190200
```csharp
201+
// Retrieve the token with the specified scopes
191202
var scope = AzureAdB2COptions.ApiScopes.Split(' ');
192203
string signedInUserID = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
193-
TokenCache userTokenCache = new MSALSessionCache(signedInUserID, this.HttpContext).GetMsalCacheInstance();
194204

195-
ConfidentialClientApplication cca = new ConfidentialClientApplication(AzureAdB2COptions.ClientId, AzureAdB2COptions.Authority, AzureAdB2COptions.RedirectUri, new ClientCredential(AzureAdB2COptions.ClientSecret), userTokenCache, null);
196-
AuthenticationResult result = await cca.AcquireTokenSilentAsync(scope, cca.Users.FirstOrDefault(), AzureAdB2COptions.Authority, false);
205+
IConfidentialClientApplication cca =
206+
ConfidentialClientApplicationBuilder.Create(AzureAdB2COptions.ClientId)
207+
.WithRedirectUri(AzureAdB2COptions.RedirectUri)
208+
.WithClientSecret(AzureAdB2COptions.ClientSecret)
209+
.WithB2CAuthority(AzureAdB2COptions.Authority)
210+
.Build();
211+
new MSALStaticCache(signedInUserID, this.HttpContext).EnablePersistence(cca.UserTokenCache);
212+
213+
var accounts = await cca.GetAccountsAsync();
214+
AuthenticationResult result = await cca.AcquireTokenSilent(scope, accounts.FirstOrDefault())
215+
.ExecuteAsync();
197216
```
198217

199-
The idea is very simple. The code creates a new instance of `ConfidentialClientApplication` with the exact same coordinates as the ones used when redeeming the authorization code at authentication time. In particular, note that the exact same cache is used.
200-
That done, all you need to do is to invoke `AcquireTokenSilentAsync`, asking for the scopes you need. MSAL will look up the cache and return any cached token which match with the requirement. If such access tokens are expired or no suitable access tokens are present, but there is an associated refresh token, MSAL will automatically use that to get a new access token and return it transparently.
218+
The idea is very simple. The code creates a new instance of `IConfidentialClientApplication` with the exact same coordinates as the ones used when redeeming the authorization code at authentication time. In particular, note that the exact same cache is used.
219+
That done, all you need to do is to invoke `AcquireTokenSilent`, asking for the scopes you need. MSAL will look up the cache and return any cached token which match with the requirement. If such access tokens are expired or no suitable access tokens are present, but there is an associated refresh token, MSAL will automatically use that to get a new access token and return it transparently.
201220

202221
In the case in which refresh tokens are not present or they fail to obtain a new access token, MSAL will throw `MsalUiRequiredException`. That means that in order to obtain the requested token, the user must go through an interactive experience.

0 commit comments

Comments
 (0)