/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Net.Http.Headers; namespace QuantConnect.Brokerages.Authentication { /// /// Provides base functionality for token-based HTTP request handling. /// Token acquisition and retry logic are delegated entirely to , /// implemented by derived classes (e.g., ). /// public abstract class LeanTokenHandler : DelegatingHandler where T : LeanTokenCredentials { /// /// Raised when authentication fails after all retry attempts are exhausted. /// Subscribers can use this to trigger graceful application shutdown. /// public event EventHandler AuthenticationFailed; /// /// A delegate used to construct an from a token type and access token string. /// private readonly Func _createAuthHeader; /// /// Initializes a new instance of the class. /// /// /// An optional delegate for creating an /// from the token type and access token. If not provided, a default implementation is used. /// /// An optional inner . If not provided, a default is used. protected LeanTokenHandler(Func createAuthHeader = null, HttpClientHandler handler = null) : base(handler ?? new HttpClientHandler()) { _createAuthHeader = createAuthHeader ?? ((tokenType, accessToken) => new AuthenticationHeaderValue(tokenType.ToString(), accessToken)); } /// /// Retrieves a valid access token for authenticating HTTP requests. /// Must be implemented by derived classes to provide token type and value, /// with optional support for caching and refresh logic. /// /// A cancellation token that can be used to cancel the token retrieval operation. /// A instance containing the token type and access token string. public abstract T GetAccessToken(CancellationToken cancellationToken); /// /// Invokes the event. /// Derived classes call this when authentication fails after exhausting all retry attempts. /// /// The exception that caused the authentication failure. protected void OnAuthenticationFailed(Exception exception) { AuthenticationFailed?.Invoke(this, exception); } /// /// Sends an HTTP request asynchronously by internally invoking the synchronous method. /// This is useful for compatibility with components that require an asynchronous pipeline, even though the core logic is synchronous. /// /// The HTTP request message to send. /// A cancellation token to cancel the operation. /// /// A task representing the asynchronous operation, containing the HTTP response message. /// protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { return Task.FromResult(Send(request, cancellationToken)); } /// /// Sends an HTTP request synchronously, applying token-based authentication. /// /// The HTTP request message to send. /// A cancellation token to cancel operation. /// The HTTP response message. protected override HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken) { var accessToken = GetAccessToken(cancellationToken); request.Headers.Authorization = _createAuthHeader(accessToken.TokenType, accessToken.AccessToken); return base.Send(request, cancellationToken); } } }