microsoft/healthcare-shared-components

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
main

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/Microsoft.Health.Client/Authentication/ManagedIdentityCredentialProvider.cs

44lines · 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 Azure.Core;
9using Azure.Identity;
10using EnsureThat;
11using Microsoft.Extensions.Options;
12
13namespace Microsoft.Health.Client.Authentication;
14
15public class ManagedIdentityCredentialProvider : CredentialProvider
16{
17 private readonly IOptionsMonitor<ManagedIdentityCredentialOptions> _managedIdentityCredentialOptionsMonitor;
18 private readonly string _optionsName;
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="managedIdentityCredentialOptionsMonitor">The configuration of the token to obtain.</param>
25 /// <param name="optionsName">Optional name to use when retrieving options from the IOptionsMonitor</param>
26 public ManagedIdentityCredentialProvider(IOptionsMonitor<ManagedIdentityCredentialOptions> managedIdentityCredentialOptionsMonitor, string optionsName = null)
27 {
28 EnsureArg.IsNotNull(managedIdentityCredentialOptionsMonitor, nameof(managedIdentityCredentialOptionsMonitor));
29
30 _managedIdentityCredentialOptionsMonitor = managedIdentityCredentialOptionsMonitor;
31 _optionsName = optionsName;
32 }
33
34 protected override async Task<string> BearerTokenFunction(CancellationToken cancellationToken)
35 {
36 ManagedIdentityCredentialOptions options = _managedIdentityCredentialOptionsMonitor.Get(_optionsName);
37 ManagedIdentityId id = string.IsNullOrEmpty(options.ClientId) ? ManagedIdentityId.SystemAssigned : ManagedIdentityId.FromUserAssignedClientId(options.ClientId);
38 ManagedIdentityCredential credential = new(id);
39
40 TokenRequestContext requestContext = new(scopes: [options.Resource], tenantId: options.TenantId);
41 AccessToken accessToken = await credential.GetTokenAsync(requestContext, cancellationToken).ConfigureAwait(false);
42 return accessToken.Token;
43 }
44}
45