public async Task <string> GetTokenAsync(string requestUri)
        {
            var scope      = requestUri;
            var credential = (ServiceBusTokenCredential)_tokenCredential;

            if (!credential.IsSharedAccessSignatureCredential)
            {
                scope = Constants.DefaultScope;
            }
            AccessToken token = await _tokenCredential.GetTokenAsync(new TokenRequestContext(new[] { scope }), CancellationToken.None).ConfigureAwait(false);

            return(token.Token);
        }
 private static async ValueTask <AccessToken> GetTokenFromCredentialAsync(TokenCredential credential, TokenRequestContext requestContext, bool async, CancellationToken cancellationToken)
 {
     try
     {
         return(async
             ? await credential.GetTokenAsync(requestContext, cancellationToken).ConfigureAwait(false)
             : credential.GetToken(requestContext, cancellationToken));
     }
     catch (Exception e) when(!(e is CredentialUnavailableException))
     {
         throw new AuthenticationFailedException(UnhandledExceptionMessage, e);
     }
 }
Ejemplo n.º 3
0
    private async ValueTask <string> GetAccessToken()
    {
        if (CachedToken.ExpiresOn > DateTime.UtcNow.AddMinutes(4))
        {
            return(CachedToken.Token);
        }

        var scopes = new[] { "https://atlas.microsoft.com/.default" };

        CachedToken = await _tokenCredential.GetTokenAsync(new TokenRequestContext(scopes), default);

        return(CachedToken.Token);
    }
Ejemplo n.º 4
0
        public static async Task <IAccessToken> GetAccessTokenAsync(
            Task <AuthenticationRecord> authTask,
            TokenCredential tokenCredential,
            TokenRequestContext requestContext,
            CancellationToken cancellationToken)
        {
            var record = await authTask;

            cancellationToken.ThrowIfCancellationRequested();
            var token = await tokenCredential.GetTokenAsync(requestContext, cancellationToken);

            return(new MsalAccessToken(tokenCredential, requestContext, token.Token, token.ExpiresOn, record.TenantId, record.Username, record.HomeAccountId));
        }
        internal virtual async Task <IAccessToken> GetAccessTokenAsync(
            Task <AuthenticationRecord> authTask,
            TokenCredential tokenCredential,
            TokenRequestContext requestContext,
            CancellationToken cancellationToken)
        {
            var record = await authTask.ConfigureAwait(false);

            cancellationToken.ThrowIfCancellationRequested();
            TracingAdapter.Information($"{DateTime.Now:T} - [MsalAccessTokenAcquirer] Calling {tokenCredential.GetType().Name}.GetTokenAsync - Scopes:'{string.Join(",", requestContext.Scopes)}'");
            var token = await tokenCredential.GetTokenAsync(requestContext, cancellationToken).ConfigureAwait(false);

            return(new MsalAccessToken(tokenCredential, requestContext, token.Token, token.ExpiresOn, record.TenantId, record.Username, record.HomeAccountId));
        }
        public async Task <AccessToken> GetTokenAsync(CancellationToken cancellationToken = default)
        {
            var cacheKey = GetCacheKey(_scopes);

            if (!_cache.TryGetValue <AccessToken>(cacheKey, out var accessToken))
            {
                accessToken = await _tokenCredential.GetTokenAsync(new TokenRequestContext(_scopes), cancellationToken)
                              .ConfigureAwait(false);

                _cache.Set(cacheKey, accessToken, accessToken.ExpiresOn - ExpirationThreshold);
            }

            return(accessToken);
        }
        private async ValueTask <string> GetAccessTokenAsync(CancellationToken cancellationToken)
        {
            if (CachedTokenValid())
            {
                return(_cachedToken.Token);
            }

            // Get access token for Azure SQL DB
            string scope = "https://database.windows.net/.default";
            var    token = await _tokenCredential.GetTokenAsync(new TokenRequestContext(new[] { scope }), cancellationToken);

            _cachedToken = token;
            return(token.Token);
        }
Ejemplo n.º 8
0
 internal static async Task<IAccessToken> GetAccessTokenAsync(
     string callerClassName,
     string parametersLog,
     TokenCredential tokenCredential,
     TokenRequestContext requestContext,
     CancellationToken cancellationToken,
     string tenantId = null,
     string userId = null,
     string homeAccountId = "")
 {
     TracingAdapter.Information($"{DateTime.Now:T} - [{callerClassName}] Calling {tokenCredential.GetType().Name}.GetTokenAsync {parametersLog}");
     var token = await tokenCredential.GetTokenAsync(requestContext, cancellationToken).ConfigureAwait(false);
     return new MsalAccessToken(tokenCredential, requestContext, token.Token, token.ExpiresOn, tenantId, userId, homeAccountId);
 }
        private async Task <List <SqlRowModel> > GetSqlRowsWithAdoNet()
        {
            var results = new List <SqlRowModel>();

            AccessToken accessToken;

            if (CachedAdoNetToken.ExpiresOn > DateTime.UtcNow.AddMinutes(4))
            {
                accessToken = CachedAdoNetToken;
            }
            else
            {
                accessToken = await _tokenCredential.GetTokenAsync(
                    new TokenRequestContext(new[] { "https://database.windows.net/" }),
                    default);

                CachedAdoNetToken = accessToken;
            }

            await using (var conn = new SqlConnection(_settings.SqlConnectionString))
            {
                conn.AccessToken = accessToken.Token;

                await conn.OpenAsync();

                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = "SELECT [Id], [Value] FROM [dbo].[Test]";
                SqlDataReader reader = await cmd.ExecuteReaderAsync();

                if (reader.HasRows)
                {
                    while (await reader.ReadAsync())
                    {
                        int    id    = (int)reader["Id"];
                        string value = (string)reader["Value"];

                        results.Add(new SqlRowModel
                        {
                            Id    = id,
                            Value = value
                        });
                    }
                }

                await reader.CloseAsync();
            }

            return(results);
        }
Ejemplo n.º 10
0
        private static async Task <TimeSeriesInsightsClient> GetTimeSeriesInsightsClientAsync(
            TokenCredential credential, string timeSeriesEnvironmentFqdn)
        {
            var token = await credential.GetTokenAsync(
                new TokenRequestContext(new[] { TimeSeriesInsightsApplicationId }), default);

            ServiceClientCredentials clientCredentials = new TokenCredentials(token.Token);

            TimeSeriesInsightsClient timeSeriesInsightsClient = new TimeSeriesInsightsClient(clientCredentials)
            {
                EnvironmentFqdn = timeSeriesEnvironmentFqdn
            };

            return(timeSeriesInsightsClient);
        }
#pragma warning disable CS1998 // Disabled as we need to throw exception for NET 451.

        // The AMQP protocol uses this method to get a CBS token for authentication.
        public async override Task <CbsToken> GetTokenAsync(Uri namespaceAddress, string appliesTo, string[] requiredClaims)
        {
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
#if NET451
            throw new InvalidOperationException($"TokenCredential is not supported on NET451");
#else
            AccessToken token = await _credential.GetTokenAsync(
                new TokenRequestContext(CommonConstants.IotHubAadTokenScopes),
                new CancellationToken()).ConfigureAwait(false);

            return(new CbsToken(
                       $"{TokenType} {token.Token}",
                       TokenType,
                       token.ExpiresOn.UtcDateTime));
#endif
        }
Ejemplo n.º 12
0
        public override async ValueTask ProcessAsync(HttpMessage message, ReadOnlyMemory <HttpPipelinePolicy> pipeline)
        {
            string token;

            if (message.Request.Headers.TryGetValue(AuthorizationHeaderKey, out string authorization) && authorization.StartsWith(BearerTokenPrefix, StringComparison.InvariantCultureIgnoreCase))
            {
                token = authorization.Substring(BearerTokenPrefix.Length);
            }
            else
            {
                token = (await _credential.GetTokenAsync(new TokenRequestContext(new[] { _scope }), default)).Token;
            }

            message.Request.Headers.SetValue(UserTokenHeader, token);
            await ProcessNextAsync(message, pipeline);
        }
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var requestContext = new TokenRequestContext(Scopes);
            var accessToken    = await TokenCredential.GetTokenAsync(requestContext, cancellationToken);

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.Token);
            var response = await base.SendAsync(request, cancellationToken);

            if (!response.IsSuccessStatusCode)
            {
                var statusDescription = response.ReasonPhrase.Replace(" ", string.Empty);
                var severity          = response.StatusCode == System.Net.HttpStatusCode.TooManyRequests ? ErrorSeverity.Informational : ErrorSeverity.Critical;
                Logger.LogMetric(FhirClientMetrics.HandledException($"{ErrorType.FHIRServiceError}{statusDescription}", severity), 1);
            }

            return(response);
        }
Ejemplo n.º 14
0
        public override async Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var token = await _cache.GetOrCreateAsync("accessToken-tokenProvider." + string.Join("#", _scopes), async e =>
            {
                var accessToken      = await _tokenCredential.GetTokenAsync(new TokenRequestContext(_scopes), cancellationToken);
                e.AbsoluteExpiration = accessToken.ExpiresOn;
                return(accessToken.Token);
            });

            request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(BearerTokenType, token);
            await base.ProcessHttpRequestAsync(request, cancellationToken).ConfigureAwait(false);
        }
        /// <inheritdoc />
        public override async ValueTask ProcessAsync(
            HttpMessage message,
            ReadOnlyMemory <HttpPipelinePolicy> pipeline)
        {
            if (_headerValue == null)
            {
                var token = await _credential.GetTokenAsync(new TokenRequestContext(Array.Empty <string>(), message.Request.ClientRequestId), message.CancellationToken).ConfigureAwait(false);

                _headerValue = "token " + token.Token;
            }
            if (_headerValue != null)
            {
                message.Request.Headers.Remove(HttpHeader.Names.Authorization);
                message.Request.Headers.Add(HttpHeader.Names.Authorization, _headerValue);
            }
            await ProcessNextAsync(message, pipeline).ConfigureAwait(false);
        }
Ejemplo n.º 16
0
        public override async ValueTask <InterceptionResult> ConnectionOpeningAsync(
            DbConnection connection,
            ConnectionEventData eventData,
            InterceptionResult result,
            CancellationToken cancellationToken = default)
        {
            var sqlConnection = (SqlConnection)connection;

            if (DoesConnectionNeedAccessToken(sqlConnection))
            {
                var tokenRequestContext = new TokenRequestContext(_azureSqlScopes);
                var token = await _credential.GetTokenAsync(tokenRequestContext, cancellationToken);

                sqlConnection.AccessToken = token.Token;
            }

            return(await base.ConnectionOpeningAsync(connection, eventData, result, cancellationToken));
        }
        public async Task <string> GetAzureManagementApiAccessTokenAsync()
        {
            var tokenRefreshTime = _cachedToken.ExpiresOn == default
                ? _cachedToken.ExpiresOn
                : _cachedToken.ExpiresOn.Subtract(TimeSpan.FromMinutes(10));

            if (DateTimeOffset.UtcNow < tokenRefreshTime)
            {
                return(_cachedToken.Token);
            }

            var scope       = "https://management.core.windows.net/.default";
            var accessToken = await _tokenCredential.GetTokenAsync(
                new TokenRequestContext(new[] { scope }), default);

            _cachedToken = accessToken;
            return(accessToken.Token);
        }
        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(UnavailbleErrorMessage));
            }

            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);
            }
        }
Ejemplo n.º 19
0
        public async Task ProcessAsync(HttpPipelineMessage message, ReadOnlyMemory <HttpPipelinePolicy> pipeline, bool async)
        {
            if (DateTimeOffset.UtcNow >= _refreshOn)
            {
                AccessToken token = async ?
                                    await _credential.GetTokenAsync(_scopes, message.CancellationToken).ConfigureAwait(false) :
                                    _credential.GetToken(_scopes, message.CancellationToken);

                _headerValue = "Bearer " + token.Token;
                _refreshOn   = token.ExpiresOn - TimeSpan.FromMinutes(2);
            }

            message.Request.SetHeader(HttpHeader.Names.Authorization, _headerValue);

            if (async)
            {
                await ProcessNextAsync(message, pipeline).ConfigureAwait(false);
            }
            else
            {
                ProcessNext(message, pipeline);
            }
        }
        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));
            }
        }
Ejemplo n.º 21
0
            protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                var requestContext = new TokenRequestContext(Scopes);
                var accessToken    = await TokenCredential.GetTokenAsync(requestContext, CancellationToken.None);

                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.Token);
                var response = await base.SendAsync(request, cancellationToken);

                if (Logger != null && !response.IsSuccessStatusCode)
                {
                    var statusDescription = response.ReasonPhrase.Replace(" ", string.Empty);

                    if (response.StatusCode == System.Net.HttpStatusCode.TooManyRequests)
                    {
                        Logger.LogMetric(FhirClientMetrics.HandledException($"FhirServerError{statusDescription}", ErrorSeverity.Informational, ConnectorOperation.FHIRConversion), 1);
                    }
                    else
                    {
                        Logger.LogMetric(FhirClientMetrics.HandledException($"FhirServerError{statusDescription}", ErrorSeverity.Critical, ConnectorOperation.FHIRConversion), 1);
                    }
                }

                return(response);
            }
Ejemplo n.º 22
0
        private async Task <string> GetAccessTokenAsync()
        {
            await _semaphoreToken.WaitAsync();

            try
            {
                //If the Token has more than 5 minutes Validity
                if (DateTime.UtcNow.AddMinutes(_cacheLifeTime) <= _token.ExpiresOn.UtcDateTime)
                {
                    return(_token.Token);
                }

                var tokenRequestContext = new TokenRequestContext(_azureSqlScopes);
                var token = await _credential.GetTokenAsync(tokenRequestContext, CancellationToken.None);

                _token = token;

                return(token.Token);
            }
            finally
            {
                _semaphoreToken.Release();
            }
        }
        public async Task ProcessAsync(HttpPipelineMessage message, ReadOnlyMemory <HttpPipelinePolicy> pipeline, bool async)
        {
            string token = async ?
                           await _credential.GetTokenAsync(_scopes, message.Cancellation).ConfigureAwait(false) :
                           _credential.GetToken(_scopes, message.Cancellation);

            if (token != _currentToken)
            {
                // Avoid per request allocations
                _currentToken = token;
                _headerValue  = "Bearer " + token;
            }

            message.Request.SetHeader(HttpHeader.Names.Authorization, _headerValue);

            if (async)
            {
                await ProcessNextAsync(pipeline, message);
            }
            else
            {
                ProcessNext(pipeline, message);
            }
        }
Ejemplo n.º 24
0
        public virtual async Task <string> GenerateAadTokenAsync(CancellationToken ctoken = default)
        {
            var token = await TokenCredential.GetTokenAsync(_defaultRequestContext, ctoken);

            return(token.Token);
        }
Ejemplo n.º 25
0
 public async override ValueTask <string> GetTokenAsync(string[] scopes, CancellationToken cancellationToken)
 {
     return((_credential != null) ? await _credential.GetTokenAsync(scopes, cancellationToken) : null);
 }
 public override ValueTask <AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)
 {
     return(_tokenCredential.GetTokenAsync(requestContext, cancellationToken));
 }
Ejemplo n.º 27
0
        /// <summary>
        /// Obtains a token from the Azure Active Directory service, using the specified client detailed specified in the SDK Auth file.
        /// This method is called by Azure SDK clients. It isn't intended for use in application code.
        /// </summary>
        /// <remarks>
        /// If the SDK Auth file is missing or invalid, this method throws a <see cref="AuthenticationFailedException"/> exception.
        /// </remarks>
        /// <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 async override ValueTask <AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)
        {
            await EnsureCredential(true, cancellationToken).ConfigureAwait(false);

            return(await _credential.GetTokenAsync(requestContext, cancellationToken).ConfigureAwait(false));
        }
 /// <summary>
 ///   Retrieves the token that represents the shared access signature credential, for
 ///   use in authorization against an Service Bus entity.
 /// </summary>
 ///
 /// <param name="requestContext">The details of the authentication request.</param>
 /// <param name="cancellationToken">The token used to request cancellation of the operation.</param>
 ///
 /// <returns>The token representing the shared access signature for this credential.</returns>
 ///
 public override ValueTask <AccessToken> GetTokenAsync(
     TokenRequestContext requestContext,
     CancellationToken cancellationToken) =>
 _credential.GetTokenAsync(requestContext, cancellationToken);