< Summary

Class:Microsoft.Azure.KeyVault.KeyVaultCredential
Assembly:Microsoft.Azure.KeyVault
File(s):C:\Git\azure-sdk-for-net\sdk\keyvault\Microsoft.Azure.KeyVault\src\Customized\Authentication\KeyVaultCredential.cs
Covered lines:23
Uncovered lines:17
Coverable lines:40
Total lines:141
Line coverage:57.5% (23 of 40)
Covered branches:10
Total branches:24
Branch coverage:41.6% (10 of 24)

Metrics

MethodCyclomatic complexity Line coverage Branch coverage
get_Token()-0%100%
.ctor(...)-100%100%
Clone()-100%100%
PreAuthenticate()-83.33%75%
PostAuthenticate()-0%0%
InitializeServiceClient(...)-83.33%50%
ProcessHttpRequestAsync()-64.29%50%

File(s)

C:\Git\azure-sdk-for-net\sdk\keyvault\Microsoft.Azure.KeyVault\src\Customized\Authentication\KeyVaultCredential.cs

#LineLine coverage
 1// Copyright (c) Microsoft Corporation. All rights reserved.
 2// Licensed under the MIT License. See License.txt in the project root for
 3// license information.
 4
 5using System;
 6using System.Linq;
 7using System.Net;
 8using System.Net.Http;
 9using System.Net.Http.Headers;
 10using System.Threading;
 11using System.Threading.Tasks;
 12using Microsoft.Rest;
 13
 14namespace Microsoft.Azure.KeyVault
 15{
 16    /// <summary>
 17    /// The Key Vault credential class that implements <see cref="ServiceClientCredentials"/>
 18    /// </summary>
 19    public class KeyVaultCredential : ServiceClientCredentials
 20    {
 21        private KeyVaultClient _client = null;
 22
 23        /// <summary>
 24        /// The authentication callback
 25        /// </summary>
 26        public event KeyVaultClient.AuthenticationCallback OnAuthenticate = null;
 27
 28        /// <summary>
 29        /// Bearer token
 30        /// </summary>
 031        public string Token { get; set; }
 32
 33        /// <summary>
 34        /// Constructor.
 35        /// </summary>
 36        /// <param name="authenticationCallback"> the authentication callback. </param>
 12237        public KeyVaultCredential(KeyVaultClient.AuthenticationCallback authenticationCallback)
 38        {
 12239            OnAuthenticate = authenticationCallback;
 12240        }
 41
 42        /// <summary>
 43        /// Clones the current KeyVaultCredential object.
 44        /// </summary>
 45        /// <returns>A new KeyVaultCredential instance using the same authentication callback as the current instance.</
 46        internal KeyVaultCredential Clone()
 47        {
 248            return new KeyVaultCredential(OnAuthenticate);
 49        }
 50
 51        private async Task<string> PreAuthenticate(Uri url)
 52        {
 253            if (OnAuthenticate != null)
 54            {
 255                var challenge = HttpBearerChallengeCache.GetInstance().GetChallengeForURL(url);
 56
 257                if (challenge != null)
 58                {
 059                    return await OnAuthenticate(challenge.AuthorizationServer, challenge.Resource, challenge.Scope).Conf
 60                }
 61            }
 62
 263            return null;
 264        }
 65
 66        protected async Task<string> PostAuthenticate(HttpResponseMessage response)
 67        {
 68            // An HTTP 401 Not Authorized error; handle if an authentication callback has been supplied
 069            if (OnAuthenticate != null)
 70            {
 71                // Extract the WWW-Authenticate header and determine if it represents an OAuth2 Bearer challenge
 072                var authenticateHeader = response.Headers.WwwAuthenticate.ElementAt(0).ToString();
 73
 074                if (HttpBearerChallenge.IsBearerChallenge(authenticateHeader))
 75                {
 076                    var challenge = new HttpBearerChallenge(response.RequestMessage.RequestUri, authenticateHeader);
 77
 078                    if (challenge != null)
 79                    {
 80                        // Update challenge cache
 081                        HttpBearerChallengeCache.GetInstance().SetChallengeForURL(response.RequestMessage.RequestUri, ch
 82
 83                        // We have an authentication challenge, use it to get a new authorization token
 084                        return await OnAuthenticate(challenge.AuthorizationServer, challenge.Resource, challenge.Scope).
 85                    }
 86                }
 87            }
 88
 089            return null;
 090        }
 91
 92        public override void InitializeServiceClient<T>(ServiceClient<T> client)
 93        {
 12094            base.InitializeServiceClient(client);
 95
 12096            var kvClient = client as KeyVaultClient;
 97
 12098            if (kvClient == null)
 99            {
 0100                throw new ArgumentException("KeyVaultCredential credentials are only for use with the KeyVaultClient ser
 101            }
 102
 120103            _client = kvClient;
 120104        }
 105
 106        public override async Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationTok
 107        {
 2108            if (request == null)
 109            {
 0110                throw new ArgumentNullException("request");
 111            }
 112
 2113            var accessToken = await PreAuthenticate(request.RequestUri).ConfigureAwait(false);
 2114            if (!string.IsNullOrEmpty(accessToken))
 0115                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
 116            else
 117            {
 118                HttpResponseMessage response;
 119
 120                // if this credential is tied to a specific KeyVaultClient reuse it's HttpClient to send the
 121                // initial unauthed request to get the challange, otherwise create a new HttpClient
 2122                HttpClient client = _client?.HttpClient ?? new HttpClient();
 123
 2124                using (var r = new HttpRequestMessage(request.Method, request.RequestUri))
 125                {
 2126                    response = await client.SendAsync(r).ConfigureAwait(false);
 2127                }
 128
 2129                if (response.StatusCode == HttpStatusCode.Unauthorized)
 130                {
 0131                    accessToken = await PostAuthenticate(response).ConfigureAwait(false);
 132
 0133                    if (!string.IsNullOrEmpty(accessToken))
 134                    {
 0135                        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
 136                    }
 137                }
 138            }
 2139        }
 140    }
 141}