microsoft/healthcare-shared-components
Publicmirrored from https://github.com/microsoft/healthcare-shared-componentsAvailable
src/Microsoft.Health.Client/ManagedIdentityCredentialProvider.cs
40lines · modecode
| 1 | // ------------------------------------------------------------------------------------------------- |
| 2 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. |
| 4 | // ------------------------------------------------------------------------------------------------- |
| 5 | |
| 6 | using System.Threading; |
| 7 | using System.Threading.Tasks; |
| 8 | using EnsureThat; |
| 9 | using Microsoft.Azure.Services.AppAuthentication; |
| 10 | using Microsoft.Extensions.Options; |
| 11 | using Microsoft.IdentityModel.Clients.ActiveDirectory; |
| 12 | |
| 13 | namespace Microsoft.Health.Client |
| 14 | { |
| 15 | public class ManagedIdentityCredentialProvider : CredentialProvider |
| 16 | { |
| 17 | private readonly ManagedIdentityCredentialConfiguration _managedIdentityCredentialConfiguration; |
| 18 | private readonly IHttpClientFactory _httpClientFactory; |
| 19 | |
| 20 | /// <summary> |
| 21 | /// Initializes a new instance of the <see cref="ManagedIdentityCredentialProvider"/> class. |
| 22 | /// This class is used to obtain a token for the configured resource via Managed Identity. |
| 23 | /// </summary> |
| 24 | /// <param name="managedIdentityCredentialConfiguration">The configuration of the token to obtain.</param> |
| 25 | /// <param name="httpClientFactory">An optional <see cref="IHttpClientFactory"/> for use within the <see cref="AzureServiceTokenProvider"/>.</param> |
| 26 | public ManagedIdentityCredentialProvider(IOptions<ManagedIdentityCredentialConfiguration> managedIdentityCredentialConfiguration, IHttpClientFactory httpClientFactory = null) |
| 27 | { |
| 28 | EnsureArg.IsNotNull(managedIdentityCredentialConfiguration?.Value, nameof(managedIdentityCredentialConfiguration)); |
| 29 | |
| 30 | _managedIdentityCredentialConfiguration = managedIdentityCredentialConfiguration.Value; |
| 31 | _httpClientFactory = httpClientFactory; |
| 32 | } |
| 33 | |
| 34 | protected override async Task<string> BearerTokenFunction(CancellationToken cancellationToken) |
| 35 | { |
| 36 | var azureServiceTokenProvider = new AzureServiceTokenProvider(httpClientFactory: _httpClientFactory); |
| 37 | return await azureServiceTokenProvider.GetAccessTokenAsync(_managedIdentityCredentialConfiguration.Resource, _managedIdentityCredentialConfiguration.TenantId, cancellationToken); |
| 38 | } |
| 39 | } |
| 40 | } |
| 41 | |