コード例 #1
0
        private async ValueTask <AccessToken> GetTokenImplAsync(bool async, TokenRequestContext requestContext, CancellationToken cancellationToken)
        {
            using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope("SharedTokenCacheCredential.GetToken", requestContext);

            try
            {
                IAccount account = async
                    ? await _account.Value.ConfigureAwait(false)
#pragma warning disable AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead.
                    : _account.Value.GetAwaiter().GetResult();

#pragma warning restore AZC0102 // Do not use GetAwaiter().GetResult(). Use the TaskExtensions.EnsureCompleted() extension method instead.


                AuthenticationResult result = await _client.AcquireTokenSilentAsync(requestContext.Scopes, account, async, cancellationToken).ConfigureAwait(false);

                return(scope.Succeeded(new AccessToken(result.AccessToken, result.ExpiresOn)));
            }
            catch (MsalUiRequiredException)
            {
                throw scope.FailWrapAndThrow(new CredentialUnavailableException($"{nameof(SharedTokenCacheCredential)} authentication unavailable. Token acquisition failed for user {_username}. Ensure that you have authenticated with a developer tool that supports Azure single sign on."));
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e);
            }
        }
コード例 #2
0
        private async ValueTask <AccessToken> GetTokenImplAsync(bool async, TokenRequestContext requestContext, CancellationToken cancellationToken)
        {
            using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope("SharedTokenCacheCredential.GetToken", requestContext);

            try
            {
                var      tenantId = TenantIdResolver.Resolve(_tenantId, requestContext);
                IAccount account  = await GetAccountAsync(tenantId, async, cancellationToken).ConfigureAwait(false);

                AuthenticationResult result = await Client.AcquireTokenSilentAsync(requestContext.Scopes, requestContext.Claims, account, tenantId, async, cancellationToken).ConfigureAwait(false);

                return(scope.Succeeded(new AccessToken(result.AccessToken, result.ExpiresOn)));
            }
            catch (MsalUiRequiredException ex)
            {
                throw scope.FailWrapAndThrow(
                          new CredentialUnavailableException(
                              $"{nameof(SharedTokenCacheCredential)} authentication unavailable. Token acquisition failed for user {_username}. Ensure that you have authenticated with a developer tool that supports Azure single sign on.",
                              ex));
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e);
            }
        }
コード例 #3
0
        private async ValueTask <AccessToken> GetTokenImplAsync(TokenRequestContext requestContext, bool async, CancellationToken cancellationToken)
        {
            using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope("VisualStudioCodeCredential.GetToken", requestContext);

            try
            {
                GetUserSettings(out var tenant, out var environmentName);

                var cloudInstance     = GetAzureCloudInstance(environmentName);
                var storedCredentials = _vscAdapter.GetCredentials(CredentialsSection, environmentName);

                if (!IsRefreshTokenString(storedCredentials))
                {
                    throw new CredentialUnavailableException("Need to re-authenticate user in VSCode Azure Account.");
                }

                var result = await _client.AcquireTokenByRefreshToken(requestContext.Scopes, storedCredentials, cloudInstance, tenant, async, cancellationToken).ConfigureAwait(false);

                return(scope.Succeeded(new AccessToken(result.AccessToken, result.ExpiresOn)));
            }
            catch (MsalUiRequiredException e)
            {
                throw scope.FailWrapAndThrow(new CredentialUnavailableException($"{nameof(VisualStudioCodeCredential)} authentication unavailable. Token acquisition failed. Ensure that you have authenticated in VSCode Azure Account.", e));
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e);
            }
        }
コード例 #4
0
        private async ValueTask <AccessToken> GetTokenImplAsync(bool async, TokenRequestContext requestContext, CancellationToken cancellationToken)
        {
            using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope("AzurePowerShellCredential.GetToken", requestContext);

            try
            {
                AccessToken token = await RequestAzurePowerShellAccessTokenAsync(async, requestContext.Scopes, cancellationToken).ConfigureAwait(false);

                return(scope.Succeeded(token));
            }
            catch (Win32Exception ex) when(ex.NativeErrorCode == ERROR_FILE_NOT_FOUND && RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                UseLegacyPowerShell = true;
                try
                {
                    AccessToken token = await RequestAzurePowerShellAccessTokenAsync(async, requestContext.Scopes, cancellationToken).ConfigureAwait(false);

                    return(scope.Succeeded(token));
                }
                catch (Exception e)
                {
                    throw scope.FailWrapAndThrow(e);
                }
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e);
            }
        }
コード例 #5
0
        private async ValueTask <AccessToken> GetTokenImplAsync(TokenRequestContext requestContext, bool async, CancellationToken cancellationToken)
        {
            using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope("VisualStudioCodeCredential.GetToken", requestContext);

            try
            {
                GetUserSettings(out var tenant, out var environmentName);
                var tenantId = TenantIdResolver.Resolve(tenant, requestContext);

                if (string.Equals(tenantId, Constants.AdfsTenantId, StringComparison.Ordinal))
                {
                    throw new CredentialUnavailableException("VisualStudioCodeCredential authentication unavailable. ADFS tenant / authorities are not supported.");
                }

                var    cloudInstance     = GetAzureCloudInstance(environmentName);
                string storedCredentials = GetStoredCredentials(environmentName);

                var result = await Client
                             .AcquireTokenByRefreshTokenAsync(requestContext.Scopes, requestContext.Claims, storedCredentials, cloudInstance, tenantId, async, cancellationToken)
                             .ConfigureAwait(false);

                return(scope.Succeeded(new AccessToken(result.AccessToken, result.ExpiresOn)));
            }
            catch (MsalUiRequiredException e)
            {
                throw scope.FailWrapAndThrow(
                          new CredentialUnavailableException(
                              $"{nameof(VisualStudioCodeCredential)} authentication unavailable. Token acquisition failed. Ensure that you have authenticated in VSCode Azure Account. " + Troubleshooting,
                              e));
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e, Troubleshooting);
            }
        }
コード例 #6
0
        private async ValueTask <AccessToken> GetTokenImplAsync(bool async, TokenRequestContext requestContext, CancellationToken cancellationToken)
        {
            using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScopeGroup("DefaultAzureCredential.GetToken", requestContext);

            try
            {
                using var asyncLock = await _credentialLock.GetLockOrValueAsync(async, cancellationToken).ConfigureAwait(false);

                AccessToken token;
                if (asyncLock.HasValue)
                {
                    token = await GetTokenFromCredentialAsync(asyncLock.Value, requestContext, async, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    TokenCredential credential;
                    (token, credential) = await GetTokenFromSourcesAsync(_sources, requestContext, async, cancellationToken).ConfigureAwait(false);

                    _sources = default;
                    asyncLock.SetValue(credential);
                }

                return(scope.Succeeded(token));
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e);
            }
        }
コード例 #7
0
        private async Task <AccessToken> GetTokenImplAsync(bool async, TokenRequestContext requestContext, CancellationToken cancellationToken)
        {
            using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope("UsernamePasswordCredential.GetToken", requestContext);
            try
            {
                AuthenticationResult result;
                if (_record != null)
                {
                    var tenantId = TenantIdResolver.Resolve(_tenantId, requestContext);
                    try
                    {
                        result = await Client.AcquireTokenSilentAsync(requestContext.Scopes, requestContext.Claims, _record, tenantId, async, cancellationToken)
                                 .ConfigureAwait(false);

                        return(scope.Succeeded(new AccessToken(result.AccessToken, result.ExpiresOn)));
                    }
                    catch (MsalUiRequiredException msalEx)
                    {
                        AzureIdentityEventSource.Singleton.UsernamePasswordCredentialAcquireTokenSilentFailed(msalEx);
                        // fall through so that AuthenticateImplAsync is called.
                    }
                }
                result = await AuthenticateImplAsync(async, requestContext, cancellationToken).ConfigureAwait(false);

                return(scope.Succeeded(new AccessToken(result.AccessToken, result.ExpiresOn)));
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e, Troubleshooting);
            }
        }
コード例 #8
0
        private async ValueTask <AccessToken> GetTokenImplAsync(TokenRequestContext requestContext, bool async, CancellationToken cancellationToken)
        {
            using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope("VisualStudioCredential.GetToken", requestContext);

            try
            {
                if (string.Equals(_tenantId, Constants.AdfsTenantId, StringComparison.Ordinal))
                {
                    throw new CredentialUnavailableException("VisualStudioCredential authentication unavailable. ADFS tenant/authorities are not supported.");
                }

                var tokenProviderPath = GetTokenProviderPath();
                var tokenProviders    = GetTokenProviders(tokenProviderPath);

                var resource          = ScopeUtilities.ScopesToResource(requestContext.Scopes);
                var processStartInfos = GetProcessStartInfos(tokenProviders, resource, cancellationToken);

                if (processStartInfos.Count == 0)
                {
                    throw new CredentialUnavailableException("No installed instance of Visual Studio was found");
                }

                var accessToken = await RunProcessesAsync(processStartInfos, async, cancellationToken).ConfigureAwait(false);

                return(scope.Succeeded(accessToken));
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e);
            }
        }
コード例 #9
0
        private async ValueTask <AccessToken> GetTokenImplAsync(bool async, TokenRequestContext requestContext, CancellationToken cancellationToken)
        {
            using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope($"{nameof(DeviceCodeCredential)}.{nameof(GetToken)}", requestContext);

            try
            {
                Exception inner = null;

                if (_record != null)
                {
                    try
                    {
                        AuthenticationResult result = await _client.AcquireTokenSilentAsync(requestContext.Scopes, (AuthenticationAccount)_record, async, cancellationToken).ConfigureAwait(false);

                        return(scope.Succeeded(new AccessToken(result.AccessToken, result.ExpiresOn)));
                    }
                    catch (MsalUiRequiredException e)
                    {
                        inner = e;
                    }
                }

                if (_disableAutomaticAuthentication)
                {
                    throw new AuthenticationRequiredException(AuthenticationRequiredMessage, requestContext, inner);
                }

                return(scope.Succeeded(await GetTokenViaDeviceCodeAsync(requestContext.Scopes, async, cancellationToken).ConfigureAwait(false)));
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e);
            }
        }
コード例 #10
0
        private async ValueTask <AccessToken> GetTokenImplAsync(bool async, TokenRequestContext requestContext, CancellationToken cancellationToken = default)
        {
            using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope($"{nameof(AuthorizationCodeCredential)}.{nameof(GetToken)}", requestContext);

            try
            {
                AccessToken token = default;

                if (_record is null)
                {
                    AuthenticationResult result = await _confidentialClient.AcquireTokenByAuthorizationCode(requestContext.Scopes, _authCode).ExecuteAsync(async, cancellationToken).ConfigureAwait(false);

                    _record = new AuthenticationRecord(result);

                    token = new AccessToken(result.AccessToken, result.ExpiresOn);
                }
                else
                {
                    AuthenticationResult result = await _confidentialClient.AcquireTokenSilent(requestContext.Scopes, (AuthenticationAccount)_record).ExecuteAsync(async, cancellationToken).ConfigureAwait(false);

                    token = new AccessToken(result.AccessToken, result.ExpiresOn);
                }

                return(scope.Succeeded(token));
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e);
            }
        }
コード例 #11
0
        private async ValueTask <AccessToken> GetTokenImplAsync(bool async, TokenRequestContext requestContext, CancellationToken cancellationToken)
        {
            using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope("AzurePowerShellCredential.GetToken", requestContext);

            try
            {
                AccessToken token = await RequestAzurePowerShellAccessTokenAsync(async, requestContext, cancellationToken).ConfigureAwait(false);

                if (_logAccountDetails)
                {
                    var accountDetails = TokenHelper.ParseAccountInfoFromToken(token.Token);
                    AzureIdentityEventSource.Singleton.AuthenticatedAccountDetails(accountDetails.ClientId, accountDetails.TenantId ?? _tenantId, accountDetails.Upn, accountDetails.ObjectId);
                }
                return(scope.Succeeded(token));
            }
            catch (Win32Exception ex) when(ex.NativeErrorCode == ERROR_FILE_NOT_FOUND && RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                UseLegacyPowerShell = true;
                try
                {
                    AccessToken token = await RequestAzurePowerShellAccessTokenAsync(async, requestContext, cancellationToken).ConfigureAwait(false);

                    if (_logAccountDetails)
                    {
                        AzureIdentityEventSource.Singleton.AuthenticatedAccountDetails(null, _tenantId, null, null);
                    }

                    return(scope.Succeeded(token));
                }
                catch (Exception e)
                {
                    throw scope.FailWrapAndThrow(e);
                }
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e);
            }
        }
コード例 #12
0
        /// <summary>
        /// Obtains a token from the Azure Active Directory service, using the specified client secret to authenticate. This method is called by Azure SDK clients. It isn't intended for use in application code.
        /// </summary>
        /// <param name="requestContext">The details of the authentication request.</param>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
        /// <returns>An <see cref="AccessToken"/> which can be used to authenticate service client calls.</returns>
        public override async ValueTask <AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken = default)
        {
            using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope("ClientSecretCredential.GetToken", requestContext);

            try
            {
                return(scope.Succeeded(await _client.AuthenticateAsync(TenantId, ClientId, ClientSecret, requestContext.Scopes, cancellationToken).ConfigureAwait(false)));
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e);
            }
        }
コード例 #13
0
        /// <summary>
        /// Obtains a token from the Azure Active Directory service, using the specified client secret to authenticate. This method is called by Azure SDK clients. It isn't intended for use in application code.
        /// </summary>
        /// <param name="requestContext">The details of the authentication request.</param>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
        /// <returns>An <see cref="AccessToken"/> which can be used to authenticate service client calls.</returns>
        public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken = default)
        {
            using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope("ClientSecretCredential.GetToken", requestContext);

            try
            {
                return(scope.Succeeded(_client.Authenticate(TenantId, ClientId, ClientSecret, requestContext.Scopes, cancellationToken)));
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e);
            }
        }
コード例 #14
0
        private async ValueTask <AccessToken> GetTokenImplAsync(bool async, TokenRequestContext requestContext, CancellationToken cancellationToken)
        {
            using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope("EnvironmentCredential.GetToken", requestContext);

            if (Credential is null)
            {
                throw scope.FailWrapAndThrow(new CredentialUnavailableException(UnavailableErrorMessage));
            }

            try
            {
                AccessToken token = async
                    ? await Credential.GetTokenAsync(requestContext, cancellationToken).ConfigureAwait(false)
                    : Credential.GetToken(requestContext, cancellationToken);

                return(scope.Succeeded(token));
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e);
            }
        }
コード例 #15
0
        private async Task <AuthenticationRecord> AuthenticateImplAsync(bool async, TokenRequestContext requestContext, CancellationToken cancellationToken)
        {
            using CredentialDiagnosticScope scope = Pipeline.StartGetTokenScope($"{nameof(InteractiveBrowserCredential)}.{nameof(Authenticate)}", requestContext);

            try
            {
                scope.Succeeded(await GetTokenViaBrowserLoginAsync(requestContext, async, cancellationToken).ConfigureAwait(false));

                return(Record);
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e);
            }
        }
コード例 #16
0
        private async ValueTask <AccessToken> GetTokenImplAsync(bool async, TokenRequestContext requestContext, CancellationToken cancellationToken)
        {
            using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope("ManagedIdentityCredential.GetToken", requestContext);

            try
            {
                AccessToken result = await _client.AuthenticateAsync(async, requestContext, cancellationToken).ConfigureAwait(false);

                return(scope.Succeeded(result));
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e);
            }
        }
コード例 #17
0
        private async ValueTask <AccessToken> GetTokenImplAsync(bool async, TokenRequestContext requestContext, CancellationToken cancellationToken)
        {
            using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope("AzureCliCredential.GetToken", requestContext);

            try
            {
                AccessToken token = await RequestCliAccessTokenAsync(async, requestContext.Scopes, cancellationToken).ConfigureAwait(false);

                return(scope.Succeeded(token));
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e);
            }
        }
コード例 #18
0
        private async Task <AuthenticationRecord> AuthenticateImplAsync(bool async, TokenRequestContext requestContext, CancellationToken cancellationToken)
        {
            using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope($"{nameof(UsernamePasswordCredential)}.{nameof(Authenticate)}", requestContext);

            try
            {
                scope.Succeeded(await GetTokenImplAsync(async, requestContext, cancellationToken).ConfigureAwait(false));

                return(_record);
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e);
            }
        }
コード例 #19
0
        /// <summary>
        /// Obtains a token from the Azure Active Directory service, using the specified client secret to authenticate. This method is called automatically by Azure SDK client libraries. You may call this method directly, but you must also handle token caching and token refreshing.
        /// </summary>
        /// <param name="requestContext">The details of the authentication request.</param>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
        /// <returns>An <see cref="AccessToken"/> which can be used to authenticate service client calls.</returns>
        public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken = default)
        {
            using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope("ClientSecretCredential.GetToken", requestContext);

            try
            {
                AuthenticationResult result = _client.AcquireTokenForClientAsync(requestContext.Scopes, false, cancellationToken).EnsureCompleted();

                return(scope.Succeeded(new AccessToken(result.AccessToken, result.ExpiresOn)));
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e);
            }
        }
コード例 #20
0
        /// <summary>
        /// Obtains a token from the Azure Active Directory service, using the specified client secret to authenticate. This method is called automatically by Azure SDK client libraries. You may call this method directly, but you must also handle token caching and token refreshing.
        /// </summary>
        /// <param name="requestContext">The details of the authentication request.</param>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
        /// <returns>An <see cref="AccessToken"/> which can be used to authenticate service client calls.</returns>
        public override async ValueTask <AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken = default)
        {
            using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope("ClientSecretCredential.GetToken", requestContext);

            try
            {
                AuthenticationResult result = await _client.AcquireTokenForClientAsync(requestContext.Scopes, true, cancellationToken).ConfigureAwait(false);

                return(scope.Succeeded(new AccessToken(result.AccessToken, result.ExpiresOn)));
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e);
            }
        }
コード例 #21
0
        public async override ValueTask <AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)
        {
            using CredentialDiagnosticScope scope = Client.Pipeline.StartGetTokenScope("ClientAssertionCredential.GetToken", requestContext);

            try
            {
                var tenantId = TenantIdResolver.Resolve(TenantId, requestContext);

                AuthenticationResult result = await Client.AcquireTokenForClientAsync(requestContext.Scopes, tenantId, true, cancellationToken).ConfigureAwait(false);

                return(scope.Succeeded(new AccessToken(result.AccessToken, result.ExpiresOn)));
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e);
            }
        }
コード例 #22
0
        private async Task <AuthenticationRecord> AuthenticateImplAsync(bool async, TokenRequestContext requestContext, CancellationToken cancellationToken)
        {
            using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope($"{nameof(DeviceCodeCredential)}.{nameof(Authenticate)}", requestContext);

            try
            {
                AccessToken token = await GetTokenViaDeviceCodeAsync(requestContext.Scopes, async, cancellationToken).ConfigureAwait(false);

                scope.Succeeded(token);

                return(_record);
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e);
            }
        }
        private async Task <AccessToken> GetTokenImplAsync(bool async, TokenRequestContext requestContext, CancellationToken cancellationToken)
        {
            using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope("UsernamePasswordCredential.GetToken", requestContext);

            try
            {
                AuthenticationResult result = await _client
                                              .AcquireTokenByUsernamePasswordAsync(requestContext.Scopes, _username, _password, async, cancellationToken)
                                              .ConfigureAwait(false);

                return(scope.Succeeded(new AccessToken(result.AccessToken, result.ExpiresOn)));
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e);
            }
        }
コード例 #24
0
        public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken)
        {
            using CredentialDiagnosticScope scope = Client.Pipeline.StartGetTokenScope("ClientAssertionCredential.GetToken", requestContext);

            try
            {
                var tenantId = TenantIdResolver.Resolve(TenantId, requestContext, AllowMultiTenantAuthentication);

                AuthenticationResult result = Client.AcquireTokenForClientAsync(requestContext.Scopes, tenantId, false, cancellationToken).EnsureCompleted();

                return(scope.Succeeded(new AccessToken(result.AccessToken, result.ExpiresOn)));
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e);
            }
        }
コード例 #25
0
        private async Task <AuthenticationResult> AuthenticateImplAsync(bool async, TokenRequestContext requestContext, CancellationToken cancellationToken)
        {
            using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope($"{nameof(UsernamePasswordCredential)}.{nameof(Authenticate)}", requestContext);
            try
            {
                var tenantId = TenantIdResolver.Resolve(_tenantId, requestContext);

                AuthenticationResult result = await Client
                                              .AcquireTokenByUsernamePasswordAsync(requestContext.Scopes, requestContext.Claims, _username, _password, tenantId, async, cancellationToken)
                                              .ConfigureAwait(false);

                _record = new AuthenticationRecord(result, _clientId);
                return(result);
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e, Troubleshooting);
            }
        }
コード例 #26
0
        private async ValueTask <AccessToken> GetTokenImplAsync(bool async, TokenRequestContext requestContext, CancellationToken cancellationToken)
        {
            using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope("ManagedIdentityCredential.GetToken", requestContext);

            try
            {
                AccessToken result = await _client.AuthenticateAsync(async, requestContext, cancellationToken).ConfigureAwait(false);

                if (_logAccountDetails)
                {
                    var accountDetails = TokenHelper.ParseAccountInfoFromToken(result.Token);
                    AzureIdentityEventSource.Singleton.AuthenticatedAccountDetails(accountDetails.ClientId ?? _clientId, accountDetails.TenantId, accountDetails.Upn, accountDetails.ObjectId);
                }
                return(scope.Succeeded(result));
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e, Troubleshooting);
            }
        }
コード例 #27
0
        private async ValueTask <AccessToken> GetTokenImplAsync(bool async, TokenRequestContext requestContext, CancellationToken cancellationToken)
        {
            using CredentialDiagnosticScope scope = Pipeline.StartGetTokenScope($"{nameof(InteractiveBrowserCredential)}.{nameof(GetToken)}", requestContext);

            try
            {
                Exception inner = null;

                if (Record != null)
                {
                    try
                    {
                        var tenantId = TenantIdResolver.Resolve(_tenantId ?? Record.TenantId, requestContext, _allowMultiTenantAuthentication);
                        AuthenticationResult result = await Client
                                                      .AcquireTokenSilentAsync(requestContext.Scopes, requestContext.Claims, Record, tenantId, async, cancellationToken)
                                                      .ConfigureAwait(false);

                        return(scope.Succeeded(new AccessToken(result.AccessToken, result.ExpiresOn)));
                    }
                    catch (MsalUiRequiredException e)
                    {
                        inner = e;
                    }
                }

                if (DisableAutomaticAuthentication)
                {
                    throw new AuthenticationRequiredException(AuthenticationRequiredMessage, requestContext, inner);
                }

                return(scope.Succeeded(await GetTokenViaBrowserLoginAsync(requestContext, async, cancellationToken).ConfigureAwait(false)));
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e);
            }
        }
コード例 #28
0
        private async ValueTask <AccessToken> GetTokenImplAsync(bool async, TokenRequestContext requestContext, CancellationToken cancellationToken)
        {
            using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope("DefaultAzureCredential.GetToken", requestContext);

            try
            {
                AccessToken token;

                if (_credential != null)
                {
                    token = async ? await _credential.GetTokenAsync(requestContext, cancellationToken).ConfigureAwait(false) : _credential.GetToken(requestContext, cancellationToken);
                }
                else
                {
                    token = await GetTokenFromSourcesAsync(async, requestContext, cancellationToken).ConfigureAwait(false);
                }

                return(scope.Succeeded(token));
            }
            catch (Exception e) when(!(e is CredentialUnavailableException))
            {
                throw scope.FailWrapAndThrow(new AuthenticationFailedException(UnhandledExceptionMessage, e));
            }
        }