-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
KeyVaultCredential.cs
141 lines (117 loc) · 5.24 KB
/
KeyVaultCredential.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
namespace Microsoft.Azure.KeyVault
{
/// <summary>
/// The Key Vault credential class that implements <see cref="ServiceClientCredentials"/>
/// </summary>
public class KeyVaultCredential : ServiceClientCredentials
{
private KeyVaultClient _client = null;
/// <summary>
/// The authentication callback
/// </summary>
public event KeyVaultClient.AuthenticationCallback OnAuthenticate = null;
/// <summary>
/// Bearer token
/// </summary>
public string Token { get; set; }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="authenticationCallback"> the authentication callback. </param>
public KeyVaultCredential(KeyVaultClient.AuthenticationCallback authenticationCallback)
{
OnAuthenticate = authenticationCallback;
}
/// <summary>
/// Clones the current KeyVaultCredential object.
/// </summary>
/// <returns>A new KeyVaultCredential instance using the same authentication callback as the current instance.</returns>
internal KeyVaultCredential Clone()
{
return new KeyVaultCredential(OnAuthenticate);
}
private async Task<string> PreAuthenticate(Uri url)
{
if (OnAuthenticate != null)
{
var challenge = HttpBearerChallengeCache.GetInstance().GetChallengeForURL(url);
if (challenge != null)
{
return await OnAuthenticate(challenge.AuthorizationServer, challenge.Resource, challenge.Scope).ConfigureAwait(false);
}
}
return null;
}
protected async Task<string> PostAuthenticate(HttpResponseMessage response)
{
// An HTTP 401 Not Authorized error; handle if an authentication callback has been supplied
if (OnAuthenticate != null)
{
// Extract the WWW-Authenticate header and determine if it represents an OAuth2 Bearer challenge
var authenticateHeader = response.Headers.WwwAuthenticate.ElementAt(0).ToString();
if (HttpBearerChallenge.IsBearerChallenge(authenticateHeader))
{
var challenge = new HttpBearerChallenge(response.RequestMessage.RequestUri, authenticateHeader);
if (challenge != null)
{
// Update challenge cache
HttpBearerChallengeCache.GetInstance().SetChallengeForURL(response.RequestMessage.RequestUri, challenge);
// We have an authentication challenge, use it to get a new authorization token
return await OnAuthenticate(challenge.AuthorizationServer, challenge.Resource, challenge.Scope).ConfigureAwait(false);
}
}
}
return null;
}
public override void InitializeServiceClient<T>(ServiceClient<T> client)
{
base.InitializeServiceClient(client);
var kvClient = client as KeyVaultClient;
if (kvClient == null)
{
throw new ArgumentException("KeyVaultCredential credentials are only for use with the KeyVaultClient service client.");
}
_client = kvClient;
}
public override async Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
var accessToken = await PreAuthenticate(request.RequestUri).ConfigureAwait(false);
if (!string.IsNullOrEmpty(accessToken))
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
else
{
HttpResponseMessage response;
// if this credential is tied to a specific KeyVaultClient reuse it's HttpClient to send the
// initial unauthed request to get the challange, otherwise create a new HttpClient
HttpClient client = _client?.HttpClient ?? new HttpClient();
using (var r = new HttpRequestMessage(request.Method, request.RequestUri))
{
response = await client.SendAsync(r).ConfigureAwait(false);
}
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
accessToken = await PostAuthenticate(response).ConfigureAwait(false);
if (!string.IsNullOrEmpty(accessToken))
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
}
}
}
}
}
}