| | 1 | | // Copyright (c) Microsoft Corporation. All rights reserved. |
| | 2 | | // Licensed under the MIT License. |
| | 3 | |
|
| | 4 | | using Azure.Core; |
| | 5 | | using Microsoft.Identity.Client; |
| | 6 | | using System; |
| | 7 | | using System.Threading; |
| | 8 | | using System.Threading.Tasks; |
| | 9 | | using System.Linq; |
| | 10 | | using System.Collections.Generic; |
| | 11 | | using System.Globalization; |
| | 12 | | using Azure.Core.Pipeline; |
| | 13 | |
|
| | 14 | | namespace Azure.Identity |
| | 15 | | { |
| | 16 | | /// <summary> |
| | 17 | | /// Authenticates using tokens in the local cache shared between Microsoft applications. |
| | 18 | | /// </summary> |
| | 19 | | public class SharedTokenCacheCredential : TokenCredential |
| | 20 | | { |
| | 21 | | internal const string NoAccountsInCacheMessage = "SharedTokenCacheCredential authentication unavailable. No acco |
| | 22 | | internal const string MultipleAccountsInCacheMessage = "SharedTokenCacheCredential authentication unavailable. M |
| | 23 | | internal const string NoMatchingAccountsInCacheMessage = "SharedTokenCacheCredential authentication unavailable. |
| | 24 | | internal const string MultipleMatchingAccountsInCacheMessage = "SharedTokenCacheCredential authentication unavai |
| | 25 | |
|
| 2 | 26 | | private static readonly ITokenCacheOptions s_DefaultCacheOptions = new SharedTokenCacheCredentialOptions(); |
| | 27 | | private readonly MsalPublicClient _client; |
| | 28 | | private readonly CredentialPipeline _pipeline; |
| | 29 | | private readonly string _tenantId; |
| | 30 | | private readonly string _username; |
| | 31 | | private readonly AuthenticationRecord _record; |
| | 32 | | private readonly Lazy<Task<IAccount>> _account; |
| | 33 | | /// <summary> |
| | 34 | | /// Creates a new <see cref="SharedTokenCacheCredential"/> which will authenticate users signed in through devel |
| | 35 | | /// </summary> |
| | 36 | | public SharedTokenCacheCredential() |
| 80 | 37 | | : this(null, null, null, null, null) |
| | 38 | | { |
| | 39 | |
|
| 80 | 40 | | } |
| | 41 | |
|
| | 42 | | /// <summary> |
| | 43 | | /// Creates a new <see cref="SharedTokenCacheCredential"/> which will authenticate users signed in through devel |
| | 44 | | /// </summary> |
| | 45 | | /// <param name="options">The client options for the newly created <see cref="SharedTokenCacheCredential"/></par |
| | 46 | | public SharedTokenCacheCredential(SharedTokenCacheCredentialOptions options) |
| 0 | 47 | | : this(options?.TenantId, options?.Username, options, null, null) |
| | 48 | | { |
| 0 | 49 | | } |
| | 50 | |
|
| | 51 | | /// <summary> |
| | 52 | | /// Creates a new <see cref="SharedTokenCacheCredential"/> which will authenticate users signed in through devel |
| | 53 | | /// </summary> |
| | 54 | | /// <param name="username">The username of the user to authenticate</param> |
| | 55 | | /// <param name="options">The client options for the newly created <see cref="SharedTokenCacheCredential"/></par |
| | 56 | | public SharedTokenCacheCredential(string username, TokenCredentialOptions options = default) |
| 0 | 57 | | : this(null, username, options, null, null) |
| | 58 | | { |
| 0 | 59 | | } |
| | 60 | |
|
| | 61 | | internal SharedTokenCacheCredential(string tenantId, string username, TokenCredentialOptions options, Credential |
| 6 | 62 | | : this(tenantId, username, options, pipeline, null) |
| | 63 | | { |
| 6 | 64 | | } |
| | 65 | |
|
| 166 | 66 | | internal SharedTokenCacheCredential(string tenantId, string username, TokenCredentialOptions options, Credential |
| | 67 | | { |
| 166 | 68 | | _tenantId = tenantId; |
| | 69 | |
|
| 166 | 70 | | _username = username; |
| | 71 | |
|
| 166 | 72 | | _record = (options as SharedTokenCacheCredentialOptions)?.AuthenticationRecord; |
| | 73 | |
|
| 166 | 74 | | _pipeline = pipeline ?? CredentialPipeline.GetInstance(options); |
| | 75 | |
|
| 166 | 76 | | _client = client ?? new MsalPublicClient(_pipeline, tenantId, Constants.DeveloperSignOnClientId, null, (opti |
| | 77 | |
|
| 166 | 78 | | _account = new Lazy<Task<IAccount>>(GetAccountAsync); |
| 166 | 79 | | } |
| | 80 | |
|
| | 81 | | /// <summary> |
| | 82 | | /// Obtains an <see cref="AccessToken"/> token for a user account silently if the user has already authenticated |
| | 83 | | /// </summary> |
| | 84 | | /// <param name="requestContext">The details of the authentication request.</param> |
| | 85 | | /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime</param> |
| | 86 | | /// <returns>An <see cref="AccessToken"/> which can be used to authenticate service client calls</returns> |
| | 87 | | public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken = d |
| | 88 | | { |
| 40 | 89 | | return GetTokenImplAsync(false, requestContext, cancellationToken).EnsureCompleted(); |
| | 90 | | } |
| | 91 | |
|
| | 92 | | /// <summary> |
| | 93 | | /// Obtains an <see cref="AccessToken"/> token for a user account silently if the user has already authenticated |
| | 94 | | /// </summary> |
| | 95 | | /// <param name="requestContext">The details of the authentication request.</param> |
| | 96 | | /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime</param> |
| | 97 | | /// <returns>An <see cref="AccessToken"/> which can be used to authenticate service client calls</returns> |
| | 98 | | public override async ValueTask<AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken |
| | 99 | | { |
| 40 | 100 | | return await GetTokenImplAsync(true, requestContext, cancellationToken).ConfigureAwait(false); |
| 14 | 101 | | } |
| | 102 | |
|
| | 103 | | private async ValueTask<AccessToken> GetTokenImplAsync(bool async, TokenRequestContext requestContext, Cancellat |
| | 104 | | { |
| 80 | 105 | | using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope("SharedTokenCacheCredential.GetToken", |
| | 106 | |
|
| | 107 | | try |
| | 108 | | { |
| 80 | 109 | | IAccount account = async |
| 80 | 110 | | ? await _account.Value.ConfigureAwait(false) |
| 80 | 111 | | #pragma warning disable AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extensi |
| 80 | 112 | | : _account.Value.GetAwaiter().GetResult(); |
| | 113 | | #pragma warning restore AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extensi |
| | 114 | |
|
| | 115 | |
|
| 36 | 116 | | AuthenticationResult result = await _client.AcquireTokenSilentAsync(requestContext.Scopes, account, asyn |
| | 117 | |
|
| 28 | 118 | | return scope.Succeeded(new AccessToken(result.AccessToken, result.ExpiresOn)); |
| | 119 | | } |
| 4 | 120 | | catch (MsalUiRequiredException) |
| | 121 | | { |
| 4 | 122 | | throw scope.FailWrapAndThrow(new CredentialUnavailableException($"{nameof(SharedTokenCacheCredential)} a |
| | 123 | | } |
| 48 | 124 | | catch (Exception e) |
| | 125 | | { |
| 48 | 126 | | throw scope.FailWrapAndThrow(e); |
| | 127 | | } |
| 28 | 128 | | } |
| | 129 | |
|
| | 130 | | private async Task<IAccount> GetAccountAsync() |
| | 131 | | { |
| 80 | 132 | | if (_record != null) |
| | 133 | | { |
| 4 | 134 | | return new AuthenticationAccount(_record); |
| | 135 | | } |
| | 136 | |
|
| 76 | 137 | | List<IAccount> accounts = (await _client.GetAccountsAsync().ConfigureAwait(false)).ToList(); |
| | 138 | |
|
| | 139 | | // filter the accounts to those matching the specified user and tenant |
| 76 | 140 | | List<IAccount> filteredAccounts = accounts.Where(a => |
| 76 | 141 | | // if _username is specified it must match the account |
| 200 | 142 | | (string.IsNullOrEmpty(_username) || string.Compare(a.Username, _username, StringComparison.OrdinalIgnore |
| 200 | 143 | | && |
| 200 | 144 | | //if _tenantId is specified it must match the account |
| 200 | 145 | | (string.IsNullOrEmpty(_tenantId) || string.Compare(a.HomeAccountId?.TenantId, _tenantId, StringCompariso |
| 76 | 146 | | ).ToList(); |
| | 147 | |
|
| 76 | 148 | | if (filteredAccounts.Count != 1) |
| | 149 | | { |
| 44 | 150 | | throw new CredentialUnavailableException(GetCredentialUnavailableMessage(accounts, filteredAccounts)); |
| | 151 | | } |
| | 152 | |
|
| 32 | 153 | | return filteredAccounts.First(); |
| 36 | 154 | | } |
| | 155 | |
|
| | 156 | | private string GetCredentialUnavailableMessage(List<IAccount> accounts, List<IAccount> filteredAccounts) |
| | 157 | | { |
| 44 | 158 | | if (accounts.Count == 0) |
| | 159 | | { |
| 16 | 160 | | return NoAccountsInCacheMessage; |
| | 161 | | } |
| | 162 | |
|
| 28 | 163 | | if (string.IsNullOrEmpty(_username) && string.IsNullOrEmpty(_tenantId)) |
| | 164 | | { |
| 4 | 165 | | return string.Format(CultureInfo.InvariantCulture, MultipleAccountsInCacheMessage); |
| | 166 | | } |
| | 167 | |
|
| 24 | 168 | | var usernameStr = string.IsNullOrEmpty(_username) ? string.Empty : $" username: {_username}"; |
| 24 | 169 | | var tenantIdStr = string.IsNullOrEmpty(_tenantId) ? string.Empty : $" tenantId: {_tenantId}"; |
| | 170 | |
|
| 24 | 171 | | if (filteredAccounts.Count == 0) |
| | 172 | | { |
| 12 | 173 | | return string.Format(CultureInfo.InvariantCulture, NoMatchingAccountsInCacheMessage, usernameStr, tenant |
| | 174 | | } |
| | 175 | |
|
| 12 | 176 | | return string.Format(CultureInfo.InvariantCulture, MultipleMatchingAccountsInCacheMessage, usernameStr, tena |
| | 177 | | } |
| | 178 | | } |
| | 179 | | } |