mirror of
https://dev.azure.com/effectory/Survey%20Software/_git/Cloud%20Engineering
synced 2026-02-27 10:45:02 +01:00
Add Sonar Client to update permissions and tags in Sonar Projects to new team structure Related work items: #125680
40 lines
1.3 KiB
C#
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;
|
|
}
|
|
} |