|
| 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Linq; |
| 6 | +using System.Text.Json; |
| 7 | +using System.Threading; |
| 8 | +using System.Threading.Tasks; |
| 9 | +using Azure.Core; |
| 10 | +using Azure.Core.Pipeline; |
| 11 | + |
| 12 | +namespace Azure.Communication |
| 13 | +{ |
| 14 | + /// <summary> |
| 15 | + /// Represents a credential that exchanges an Entra token for an Azure Communication Services (ACS) token, enabling access to ACS resources. |
| 16 | + /// </summary> |
| 17 | + internal sealed class EntraTokenCredential : ICommunicationTokenCredential |
| 18 | + { |
| 19 | + private const string TeamsExtensionScopePrefix = "https://auth.msft.communication.azure.com/"; |
| 20 | + private const string ComunicationClientsScopePrefix = "https://communication.azure.com/clients/"; |
| 21 | + private const string TeamsExtensionEndpoint = "/access/teamsPhone/:exchangeAccessToken"; |
| 22 | + private const string TeamsExtensionApiVersion = "2025-03-02-preview"; |
| 23 | + private const string ComunicationClientsEndpoint = "/access/entra/:exchangeAccessToken"; |
| 24 | + private const string ComunicationClientsApiVersion = "2024-04-01-preview"; |
| 25 | + |
| 26 | + private HttpPipeline _pipeline; |
| 27 | + private string _resourceEndpoint; |
| 28 | + private string[] _scopes { get; set; } |
| 29 | + private readonly ThreadSafeRefreshableAccessTokenCache _accessTokenCache; |
| 30 | + |
| 31 | + /// <summary> |
| 32 | + /// Initializes a new instance of <see cref="EntraTokenCredential"/>. |
| 33 | + /// </summary> |
| 34 | + /// <param name="options">The options for how the token will be fetched</param> |
| 35 | + /// <param name="pipelineTransport">Only for testing.</param> |
| 36 | + public EntraTokenCredential(EntraCommunicationTokenCredentialOptions options, HttpPipelineTransport pipelineTransport = null) |
| 37 | + { |
| 38 | + this._resourceEndpoint = options.ResourceEndpoint; |
| 39 | + this._scopes = options.Scopes; |
| 40 | + _pipeline = CreatePipelineFromOptions(options, pipelineTransport); |
| 41 | + _accessTokenCache = new ThreadSafeRefreshableAccessTokenCache( |
| 42 | + ExchangeEntraToken, |
| 43 | + ExchangeEntraTokenAsync, |
| 44 | + false, null, null); |
| 45 | + _accessTokenCache.GetValueAsync(default); |
| 46 | + } |
| 47 | + |
| 48 | + private HttpPipeline CreatePipelineFromOptions(EntraCommunicationTokenCredentialOptions options, HttpPipelineTransport pipelineTransport) |
| 49 | + { |
| 50 | + var authenticationPolicy = new BearerTokenAuthenticationPolicy(options.TokenCredential, options.Scopes); |
| 51 | + var entraTokenGuardPolicy = new EntraTokenGuardPolicy(); |
| 52 | + var clientOptions = ClientOptions.Default; |
| 53 | + if (pipelineTransport != null) |
| 54 | + { |
| 55 | + clientOptions.Transport = pipelineTransport; |
| 56 | + } |
| 57 | + return HttpPipelineBuilder.Build(clientOptions, authenticationPolicy, entraTokenGuardPolicy); |
| 58 | + } |
| 59 | + |
| 60 | + /// <inheritdoc /> |
| 61 | + public void Dispose() |
| 62 | + { |
| 63 | + _pipeline = default; |
| 64 | + _accessTokenCache.Dispose(); |
| 65 | + } |
| 66 | + |
| 67 | + /// <summary> |
| 68 | + /// Gets an <see cref="AccessToken"/>. |
| 69 | + /// </summary> |
| 70 | + /// <param name="cancellationToken">The cancellation token for the task.</param> |
| 71 | + /// <returns> Contains the access token.</returns> |
| 72 | + public AccessToken GetToken(CancellationToken cancellationToken = default) |
| 73 | + => _accessTokenCache.GetValue(cancellationToken, () => true); |
| 74 | + |
| 75 | + /// <summary> |
| 76 | + /// Gets an <see cref="AccessToken"/>. |
| 77 | + /// </summary> |
| 78 | + /// <param name="cancellationToken">The cancellation token for the task.</param> |
| 79 | + /// <returns> |
| 80 | + /// A task that represents the asynchronous get token operation. The value of its <see cref="ValueTask{AccessToken}.Result"/> property contains the access token. |
| 81 | + /// </returns> |
| 82 | + public ValueTask<AccessToken> GetTokenAsync(CancellationToken cancellationToken = default) |
| 83 | + => _accessTokenCache.GetValueAsync(cancellationToken, () => true); |
| 84 | + |
| 85 | + private AccessToken ExchangeEntraToken(CancellationToken cancellationToken) |
| 86 | + { |
| 87 | + return ExchangeEntraTokenAsync(false, cancellationToken).EnsureCompleted(); |
| 88 | + } |
| 89 | + |
| 90 | + private async ValueTask<AccessToken> ExchangeEntraTokenAsync(CancellationToken cancellationToken) |
| 91 | + { |
| 92 | + var result = await ExchangeEntraTokenAsync(true, cancellationToken).ConfigureAwait(false); |
| 93 | + return result; |
| 94 | + } |
| 95 | + |
| 96 | + private async ValueTask<AccessToken> ExchangeEntraTokenAsync(bool async, CancellationToken cancellationToken) |
| 97 | + { |
| 98 | + var message = CreateRequestMessage(); |
| 99 | + if (async) |
| 100 | + { |
| 101 | + await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); |
| 102 | + } |
| 103 | + else |
| 104 | + { |
| 105 | + _pipeline.Send(message, cancellationToken); |
| 106 | + } |
| 107 | + return ParseAccessTokenFromResponse(message.Response); |
| 108 | + } |
| 109 | + |
| 110 | + private HttpMessage CreateRequestMessage() |
| 111 | + { |
| 112 | + var message = _pipeline.CreateMessage(); |
| 113 | + var request = message.Request; |
| 114 | + request.Uri = CreateRequestUri(); |
| 115 | + request.Method = RequestMethod.Post; |
| 116 | + request.Headers.Add("Accept", "application/json"); |
| 117 | + request.Headers.Add("Content-Type", "application/json"); |
| 118 | + request.Content = "{}"; |
| 119 | + |
| 120 | + return message; |
| 121 | + } |
| 122 | + |
| 123 | + private RequestUriBuilder CreateRequestUri() |
| 124 | + { |
| 125 | + var uri = new RequestUriBuilder(); |
| 126 | + uri.Reset(new Uri(_resourceEndpoint)); |
| 127 | + |
| 128 | + var (endpoint, apiVersion) = DetermineEndpointAndApiVersion(); |
| 129 | + uri.AppendPath(endpoint, false); |
| 130 | + uri.AppendQuery("api-version", apiVersion, true); |
| 131 | + return uri; |
| 132 | + } |
| 133 | + |
| 134 | + private (string Endpoint, string ApiVersion) DetermineEndpointAndApiVersion() |
| 135 | + { |
| 136 | + if (_scopes == null || !_scopes.Any()) |
| 137 | + { |
| 138 | + throw new ArgumentException($"Scopes validation failed. Ensure all scopes start with either {TeamsExtensionScopePrefix} or {ComunicationClientsScopePrefix}.", nameof(_scopes)); |
| 139 | + } |
| 140 | + else if (_scopes.All(item => item.StartsWith(TeamsExtensionScopePrefix))) |
| 141 | + { |
| 142 | + return (TeamsExtensionEndpoint, TeamsExtensionApiVersion); |
| 143 | + } |
| 144 | + else if (_scopes.All(item => item.StartsWith(ComunicationClientsScopePrefix))) |
| 145 | + { |
| 146 | + return (ComunicationClientsEndpoint, ComunicationClientsApiVersion); |
| 147 | + } |
| 148 | + else |
| 149 | + { |
| 150 | + throw new ArgumentException($"Scopes validation failed. Ensure all scopes start with either {TeamsExtensionScopePrefix} or {ComunicationClientsScopePrefix}.", nameof(_scopes)); |
| 151 | + } |
| 152 | + } |
| 153 | + |
| 154 | + private AccessToken ParseAccessTokenFromResponse(Response response) |
| 155 | + { |
| 156 | + switch (response.Status) |
| 157 | + { |
| 158 | + case 200: |
| 159 | + try |
| 160 | + { |
| 161 | + var json = JsonDocument.Parse(response.Content); |
| 162 | + var accessTokenJson = json.RootElement.GetProperty("accessToken").GetRawText(); |
| 163 | + var acsToken = JsonSerializer.Deserialize<AcsToken>(accessTokenJson); |
| 164 | + return new AccessToken(acsToken.token, acsToken.expiresOn); |
| 165 | + } |
| 166 | + catch (Exception) |
| 167 | + { |
| 168 | + throw new RequestFailedException(response); |
| 169 | + } |
| 170 | + default: |
| 171 | + throw new RequestFailedException(response); |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + private class AcsToken |
| 176 | + { |
| 177 | + public string token { get; set; } |
| 178 | + public DateTimeOffset expiresOn { get; set; } |
| 179 | + } |
| 180 | + } |
| 181 | +} |
0 commit comments