microsoft/healthcare-shared-components

Public

mirrored from https://github.com/microsoft/healthcare-shared-componentsAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
1.0.0-1.0.79

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

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
6using System.Threading;
7using System.Threading.Tasks;
8using EnsureThat;
9using Microsoft.Azure.Services.AppAuthentication;
10using Microsoft.Extensions.Options;
11using Microsoft.IdentityModel.Clients.ActiveDirectory;
12
13namespace 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