Beispiel #1
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.Failed(new CredentialUnavailableException(UnavailbleErrorMessage));
            }

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

                return(scope.Succeeded(token));
            }
            catch (OperationCanceledException e)
            {
                scope.Failed(e);

                throw;
            }
            catch (Exception e)
            {
                throw scope.FailAndWrap(e);
            }
        }
Beispiel #2
0
        /// <inheritdoc />
        private async ValueTask ProcessAsync(HttpMessage message, ReadOnlyMemory <HttpPipelinePolicy> pipeline, bool async)
        {
            if (message.Request.Uri.Scheme != Uri.UriSchemeHttps)
            {
                throw new InvalidOperationException("Bearer token authentication is not permitted for non TLS protected (https) endpoints.");
            }

            if (DateTimeOffset.UtcNow >= _refreshOn)
            {
                AccessToken token = async ?
                                    await _credential.GetTokenAsync(new TokenRequestContext(_scopes, message.Request.ClientRequestId), message.CancellationToken).ConfigureAwait(false) :
                                    _credential.GetToken(new TokenRequestContext(_scopes, message.Request.ClientRequestId), message.CancellationToken);

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

            if (_headerValue != null)
            {
                message.Request.SetHeader(HttpHeader.Names.Authorization, _headerValue);
            }

            if (async)
            {
                await ProcessNextAsync(message, pipeline).ConfigureAwait(false);
            }
            else
            {
                ProcessNext(message, pipeline);
            }
        }
Beispiel #3
0
        private ExtendedAccessToken GetTokenImpl(TokenRequestContext requestContext, CancellationToken cancellationToken)
        {
            using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope("Azure.Identity.EnvironmentCredential.GetToken", requestContext);

            if (_credential is null)
            {
                return(new ExtendedAccessToken(scope.Failed(new CredentialUnavailableException(_unavailbleErrorMessage))));
            }

            try
            {
                AccessToken token = _credential.GetToken(requestContext, cancellationToken);

                return(new ExtendedAccessToken(scope.Succeeded(token)));
            }
            catch (OperationCanceledException e)
            {
                scope.Failed(e);

                throw;
            }
            catch (Exception e)
            {
                return(new ExtendedAccessToken(scope.Failed(e)));
            }
        }
Beispiel #4
0
        public async ValueTask ProcessAsync(HttpPipelineMessage message, ReadOnlyMemory <HttpPipelinePolicy> pipeline, bool async)
        {
            if (DateTimeOffset.UtcNow >= _refreshOn)
            {
                AccessToken token = async ?
                                    await _credential.GetTokenAsync(new TokenRequest(_scopes), message.CancellationToken).ConfigureAwait(false) :
                                    _credential.GetToken(new TokenRequest(_scopes), message.CancellationToken);

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

            if (_headerValue != null)
            {
                message.Request.SetHeader(HttpHeader.Names.Authorization, _headerValue);
            }

            if (async)
            {
                await ProcessNextAsync(message, pipeline).ConfigureAwait(false);
            }
            else
            {
                ProcessNext(message, pipeline);
            }
        }
        public void CreateGetTokenCallsDelegate(TokenCredential credential)
        {
            AccessToken actualToken = credential.GetToken(new TokenRequestContext(scopes), ctx);

            Assert.AreEqual(expectedToken, actualToken.Token);
            Assert.AreEqual(expires, actualToken.ExpiresOn);
        }
        public AccessTokenResponse GetAccessToken(string[] scopes, bool forceRefresh = false)
        {
            _log.LogInformation($"Getting token via {_cred.GetType()} for {string.Join(',', scopes)}");
            var b        = _cred.GetToken(new Azure.Core.TokenRequestContext(scopes), CancellationToken.None);
            var resource = ScopeUtil.GetResourceFromScope(scopes);

            return(new AccessTokenResponse(resource, b.Token, b.ExpiresOn));
        }
        public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken)
        {
            if (credential is null)
            {
                throw new CredentialUnavailableException("No configured Azure Identity options.");
            }

            return(credential.GetToken(requestContext, cancellationToken));
        }
 private void Renew()
 {
     if (IsNearExpiration())
     {
         var token = TokenCredential.GetToken(TokenRequestContext, default(CancellationToken));
         AccessToken = token.Token;
         ExpiresOn   = token.ExpiresOn;
     }
 }
        private async Task AddHeaders(HttpMessage message, bool async)
        {
            using var cts = new CancellationTokenSource(_getTokenTimeout);

            AccessToken token = async
                ? await _credential.GetTokenAsync(new TokenRequestContext(), cts.Token).ConfigureAwait(false)
                : _credential.GetToken(new TokenRequestContext(), cts.Token);

            message.Request.Headers.Add(HttpHeader.Names.Authorization, token.Token);
        }
        private string GetAccessToken()
        {
            if (CachedTokenIsValid())
            {
                return(_cachedToken.Token);
            }

            _cachedToken = _tokenCredential.GetToken(new TokenRequestContext(Scopes), default);
            return(_cachedToken.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);
     }
 }
        /// <summary>
        /// Configures the RestSharp RestClient.
        /// </summary>
        private void ConfigureRestClient()
        {
            if (!isConfigured)
            {
                Exception exceptionInLock = null;
                lock (configLock)
                {
                    if (!isConfigured)
                    {
                        try
                        {
                            var amsAccessToken = _tokenCredential.GetToken(
                                new TokenRequestContext(
                                    scopes: new[] { "https://rest.media.azure.net/.default" },
                                    parentRequestId: null),
                                default);

                            _restClient.Authenticator = new JwtAuthenticator(amsAccessToken.Token);

                            _restClient.UseNewtonsoftJson(
                                new Newtonsoft.Json.JsonSerializerSettings()
                            {
                                ContractResolver = new DefaultContractResolver(),
                            });

                            _restClient.AddDefaultHeader("Content-Type", $"{ContentType.Json};odata=verbose");
                            _restClient.AddDefaultHeader("Accept", $"{ContentType.Json};odata=verbose");
                            _restClient.AddDefaultHeader("DataServiceVersion", "3.0");
                            _restClient.AddDefaultHeader("MaxDataServiceVersion", "3.0");
                            _restClient.AddDefaultHeader("x-ms-version", "2.19");
                        }
                        catch (Exception e)
                        {
                            exceptionInLock = e;
                            _log.LogError(e, $"Failed to {nameof(ConfigureRestClient)}");
                        }
                        finally
                        {
                            isConfigured = true;
                        }
                    }
                }

                if (exceptionInLock != null)
                {
                    throw exceptionInLock;
                }
            }

            return;
        }
Beispiel #13
0
        public override string GetAuthorizationHeader()
        {
            lock (_tokenLock)
            {
                // A new token is generated if it is the first time or the cached token is close to expiry.
                if (!_cachedAccessToken.HasValue ||
                    TokenHelper.IsCloseToExpiry(_cachedAccessToken.Value.ExpiresOn))
                {
                    _cachedAccessToken = _credential.GetToken(
                        new TokenRequestContext(CommonConstants.IotHubAadTokenScopes),
                        new CancellationToken());
                }
            }

            return($"Bearer {_cachedAccessToken.Value.Token}");
        }
        /// <summary> Gets the rank processor initiated with live model to use </summary>
        internal virtual RlNetProcessor GetConfigurationForRankProcessor(CancellationToken cancellationToken = default)
        {
            Configuration config = new Configuration();

            // set up the model
            if (azureKeyCredential != null)
            {
                config["http.api.key"] = azureKeyCredential.Key;
            }
            else if (tokenCredential != null)
            {
                var         tokenRequestContext = new TokenRequestContext(scopes);
                AccessToken token = tokenCredential.GetToken(tokenRequestContext, cancellationToken);
                config["http.api.key"]             = "Bearer " + token.Token;
                config["http.api.header.key.name"] = "Authorization";
                tokenExpiry = token.ExpiresOn;
            }
            else
            {
                throw new ApplicationException("PersonalizerClient is neither initalized with Token Credential nor with AzureKey Credential");
            }
            personalizerServiceProperties = ServiceConfigurationRestClient.Get(cancellationToken);
            personalizerPolicy            = PolicyRestClient.Get(cancellationToken);
            //interactions & observations
            config["interaction.http.api.host"]         = stringEndpoint + "personalizer/v1.1-preview.3/logs/interactions";
            config["observation.http.api.host"]         = stringEndpoint + "personalizer/v1.1-preview.3/logs/observations";
            config["interaction.sender.implementation"] = "INTERACTION_HTTP_API_SENDER";
            config["observation.sender.implementation"] = "OBSERVATION_HTTP_API_SENDER";
            config["interaction.subsample.rate"]        = Convert.ToString(this.subsampleRate, CultureInfo.InvariantCulture);
            config["observation.subsample.rate"]        = Convert.ToString(this.subsampleRate, CultureInfo.InvariantCulture);
            //model
            config["model.blob.uri"] = stringEndpoint + "personalizer/v1.1-preview.3/model";
            config["model.source"]   = "HTTP_MODEL_DATA";

            config["model.vw.initial_command_line"] = personalizerPolicy.Arguments;
            config["protocol.version"]            = "2";
            config["initial_exploration.epsilon"] = Convert.ToString(personalizerServiceProperties.ExplorationPercentage, CultureInfo.InvariantCulture);
            config["rank.learning.mode"]          = Convert.ToString(personalizerServiceProperties.LearningMode, CultureInfo.InvariantCulture);
            LiveModel liveModel = new LiveModel(config);

            liveModel.Init();
            LiveModelBase liveModelAdapter = new LiveModelAdapter(liveModel);

            liveModelLastRefresh = DateTimeOffset.UtcNow;
            return(new RlNetProcessor(liveModelAdapter));
        }
Beispiel #15
0
        public override InterceptionResult ConnectionOpening(
            DbConnection connection,
            ConnectionEventData eventData,
            InterceptionResult result)
        {
            var sqlConnection = (SqlConnection)connection;

            if (DoesConnectionNeedAccessToken(sqlConnection))
            {
                var tokenRequestContext = new TokenRequestContext(_azureSqlScopes);
                var token = _credential.GetToken(tokenRequestContext, default);

                sqlConnection.AccessToken = token.Token;
            }

            return(base.ConnectionOpening(connection, eventData, result));
        }
        // The HTTP protocol uses this method to get the bearer token for authentication.
        public override string GetAuthorizationHeader()
        {
#if NET451
            throw new InvalidOperationException($"TokenCredential is not supported on NET451");
#else
            lock (_tokenLock)
            {
                // A new token is generated if it is the first time or the cached token is close to expiry.
                if (!_cachedAccessToken.HasValue ||
                    TokenHelper.IsCloseToExpiry(_cachedAccessToken.Value.ExpiresOn))
                {
                    _cachedAccessToken = _credential.GetToken(
                        new TokenRequestContext(CommonConstants.IotHubAadTokenScopes),
                        new CancellationToken());
                }
            }

            return($"{TokenType} {_cachedAccessToken.Value.Token}");
#endif
        }
Beispiel #17
0
        private string GetAccessToken()
        {
            _semaphoreToken.Wait();
            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 = _credential.GetToken(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);
            }
        }
Beispiel #19
0
        /// <summary>
        /// This should be called before any call to <see cref="IRestClient"/>,
        /// it sets up the auth token and default headers per the AMS V2 API specification.
        /// </summary>
        private void ConfigureRestClient()
        {
            var amsAccessToken = _tokenCredential.GetToken(
                new TokenRequestContext(
                    scopes: new[] { "https://rest.media.azure.net/.default" },
                    parentRequestId: null),
                default);

            _restClient.Authenticator = new JwtAuthenticator(amsAccessToken.Token);

            _restClient.UseNewtonsoftJson(
                new Newtonsoft.Json.JsonSerializerSettings()
            {
                ContractResolver = new DefaultContractResolver(),
            });

            _restClient.AddDefaultHeader("Content-Type", $"{ContentType.Json};odata=verbose");
            _restClient.AddDefaultHeader("Accept", $"{ContentType.Json};odata=verbose");
            _restClient.AddDefaultHeader("DataServiceVersion", "3.0");
            _restClient.AddDefaultHeader("MaxDataServiceVersion", "3.0");
            _restClient.AddDefaultHeader("x-ms-version", "2.19");

            return;
        }
Beispiel #20
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 override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken)
        {
            EnsureCredential(false, cancellationToken).GetAwaiter().GetResult();

            return(_credential.GetToken(requestContext, cancellationToken));
        }
 public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken)
 {
     return(_tokenCredential.GetToken(requestContext, cancellationToken));
 }
 /// <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 AccessToken GetToken(
     TokenRequestContext requestContext,
     CancellationToken cancellationToken) =>
 _credential.GetToken(requestContext, cancellationToken);
Beispiel #23
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 (OperationCanceledException e)
            {
                scope.Failed(e);
                throw;
            }
            catch (Exception e) when(!(e is CredentialUnavailableException))
            {
                throw scope.FailAndWrap(new AuthenticationFailedException(UnhandledExceptionMessage, e));
            }
        }
 /// <summary>
 /// Obtains a token from the Azure Active Directory service, using the specified client details specified in the environment variables
 /// AZURE_TENANT_ID, AZURE_CLIENT_ID, and AZURE_CLIENT_SECRET to authenticate.
 /// </summary>
 /// <remarks>
 /// If the environment variables AZURE_TENANT_ID, AZURE_CLIENT_ID, and AZURE_CLIENT_SECRET are not specified, the default <see cref="AccessToken"/>
 /// </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 override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken = default)
 {
     return((_credential != null) ? _credential.GetToken(requestContext, cancellationToken) : default);
 /// <summary>
 /// Obtains a token from the Azure Active Directory service, using the specified client details specified in the environment variables
 /// AZURE_TENANT_ID, AZURE_CLIENT_ID, and AZURE_CLIENT_SECRET to authenticate.
 /// </summary>
 /// <remarks>
 /// If the environment variables AZURE_TENANT_ID, AZURE_CLIENT_ID, and AZURE_CLIENT_SECRET are not specified, the default <see cref="AccessToken"/>
 /// </remarks>
 /// <param name="scopes">The list of scopes for which the token will have access.</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(string[] scopes, CancellationToken cancellationToken = default)
 {
     return((_credential != null) ? _credential.GetToken(scopes, cancellationToken) : default);
Beispiel #26
0
 public override string GetToken(string[] scopes, CancellationToken cancellationToken)
 {
     return(_credential?.GetToken(scopes, cancellationToken));
 }