Skip to content

Commit 808439c

Browse files
update how to get token using MSAL
1 parent 368652d commit 808439c

File tree

1 file changed

+29
-6
lines changed

1 file changed

+29
-6
lines changed

articles/applied-ai-services/immersive-reader/how-to-cache-token.md

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,15 +19,38 @@ This article demonstrates how to cache the authentication token in order to impr
1919

2020
## Using ASP.NET
2121

22-
Import the **Microsoft.IdentityModel.Clients.ActiveDirectory** NuGet package, which is used to acquire a token. Next, use the following code to acquire an `AuthenticationResult`, using the authentication values you got when you [created the Immersive Reader resource](./how-to-create-immersive-reader.md).
22+
Import the **Microsoft.Identity.Client** NuGet package, which is used to acquire a token. Next, use the following code to acquire an `AuthenticationResult`, using the authentication values you got when you [created the Immersive Reader resource](./how-to-create-immersive-reader.md).
23+
24+
Create a confidential client application property.
2325

2426
```csharp
25-
private async Task<AuthenticationResult> GetTokenAsync()
27+
private IConfidentialClientApplication _confidentialClientApplication;
28+
private IConfidentialClientApplication ConfidentialClientApplication
2629
{
27-
AuthenticationContext authContext = new AuthenticationContext($"https://login.windows.net/{TENANT_ID}");
28-
ClientCredential clientCredential = new ClientCredential(CLIENT_ID, CLIENT_SECRET);
29-
AuthenticationResult authResult = await authContext.AcquireTokenAsync("https://cognitiveservices.azure.com/", clientCredential);
30-
return authResult;
30+
get {
31+
if (_confidentialClientApplication == null) {
32+
_confidentialClientApplication = ConfidentialClientApplicationBuilder.Create(ClientId)
33+
.WithClientSecret(ClientSecret)
34+
.WithAuthority($"https://login.windows.net/{TenantId}")
35+
.Build();
36+
}
37+
38+
return _confidentialClientApplication;
39+
}
40+
}
41+
```
42+
43+
```csharp
44+
public async Task<string> GetTokenAsync()
45+
{
46+
const string resource = "https://cognitiveservices.azure.com/";
47+
48+
var authResult = await ConfidentialClientApplication.AcquireTokenForClient(
49+
new[] { $"{resource}/.default" })
50+
.ExecuteAsync()
51+
.ConfigureAwait(false);
52+
53+
return authResult.AccessToken;
3154
}
3255
```
3356

0 commit comments

Comments
 (0)