简体   繁体   中英

What is the best practice for adding a token to an HTTP header in MSAL?

When I sign in, get a token silently:

            var accounts = await this.PublicClientApplication.GetAccountsAsync().ConfigureAwait(false);
            foreach (IAccount account in accounts)
            {
                var authenticationResult = await this.PublicClientApplication.AcquireTokenSilent(this.Scopes, account)
                    .ExecuteAsync(cancellationToken)
                    .ConfigureAwait(false);
                this.Account = authenticationResult.Account;
                return true;
            }

Now that I have a token and I can add it to my HTTP headers. But I have a program that's running continuously, hours or days, many tasks.

So What's the best practice for managing the lifetime of the token?

Should I wait until I take an exception with the existing token and then try this function again? Or should I just trust the credential cache to manage the token lifetime for me by doing something like this before each invocation of an HttpClient call:

                // Get the cached credentials for the currently selected account.
                AuthenticationResult authenticationResult = await this.host.PublicClientApplication
                    .AcquireTokenSilent(this.host.Scopes, this.host.Account)
                    .ExecuteAsync(cancellationToken)
                    .ConfigureAwait(false);

                // Update the request header with the security token acquired from the authentication service.
                lock (this.headerLock)
                {
                    this.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);
                }

                request.Content = stringContent;
                using (HttpResponseMessage response = await this.httpClient.SendAsync(request).ConfigureAwait(true))
                 {
                     // Report any errors.
                     if (!response.IsSuccessStatusCode)
                     {
                         this.logger.LogError($"{(int)response.StatusCode}: {response.ReasonPhrase}");
                      }
                  }

This page from Microsoft seems to confirm the best pattern is the second one: grab a token before each HttpClient call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM