private async Task EnsureValidAccessTokenAsync(CancellationToken cancellationToken)
 {
     if (_accessToken == null || !_accessToken.IsValid())
     {
         var securityToken = _client.GetSecurityToken();
         _accessToken = await _client.GetAccessTokenAsync(securityToken, cancellationToken);
     }
 }
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var response = await SendAuthenticatedRequest(request, cancellationToken);

            if (response.StatusCode == HttpStatusCode.Unauthorized && IsInvalidToken(response))
            {
                //if the request is denied due to the token no longer being valid, we flush the tokens, ensure they are reloaded, and refire the request
                _accessToken = null;
                response     = await SendAuthenticatedRequest(request, cancellationToken);
            }

            return(response);
        }
        /// <summary>
        /// Constructor that always uses a client certificate if one exist for TLS client authentication.
        /// </summary>
        /// <param name="client">Backpointer to OioIdwsClient</param>
        /// <param name="accessToken">An optional access token. Can be used if client already has access to a cached token.</param>
        public OioIdwsRequestHandler(OioIdwsClient client, AccessToken.AccessToken accessToken)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            _client      = client;
            _accessToken = accessToken;

            //We can't know in advance whether it's a Bearer/Holder-of-key token we're going to work with. Either way we just add the certificate to the request, if given
            if (client.Settings.ClientCertificate != null)
            {
                ClientCertificates.Add(client.Settings.ClientCertificate);
            }
        }