Files
Cloud-20Engineering/ConsoleApps/AzureRestApi/AzureRestApi/Repositories/AccessTokenRepository.cs
Johannes Oenema Effectory 91980817e0 Merged PR 63702: Add Sonar Client to update permissions and tags in Sonar Projects to new team structure
Add Sonar Client to update permissions and tags in Sonar Projects to new team structure

Related work items: #125680
2025-11-05 15:18:52 +00:00

40 lines
1.3 KiB
C#

using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using AzureRestApi.Models;
using Microsoft.Identity.Client;
namespace AzureRestApi.Repositories;
public class AccessTokenRepository(Settings settings)
{
private string? _accessToken;
public async Task<string> GetAccessToken()
{
if (!string.IsNullOrWhiteSpace(_accessToken)) return _accessToken;
var keyVaultUri = "https://" + settings.KeyVaultName + ".vault.azure.net";
var credential = new DefaultAzureCredential();
var client = new SecretClient(new Uri(keyVaultUri), credential);
var clientId = (await client.GetSecretAsync("ClientID")).Value.Value;
var clientSecret = (await client.GetSecretAsync("ClientSecret")).Value.Value;
var app = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority(new Uri($"https://login.microsoftonline.com/{settings.AzureTenantId}"))
.Build();
var scopes = new[] {"https://management.azure.com/.default"};
var result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the Access token");
}
_accessToken = result.AccessToken;
return _accessToken;
}
}