-
Notifications
You must be signed in to change notification settings - Fork 287
/
ReflectionCredentialEnvelope.cs
216 lines (187 loc) · 11.3 KB
/
ReflectionCredentialEnvelope.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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
namespace Microsoft.ApplicationInsights.Extensibility.Implementation.Authentication
{
using System;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// This is an envelope for an instance of Azure.Core.TokenCredential.
/// This class uses reflection to interact with the Azure.Core library.
/// </summary>
/// <remarks>
/// Our SDK currently targets net452, net46, and netstandard2.0.
/// Azure.Core.TokenCredential is only available for netstandard2.0.
/// </remarks>
internal class ReflectionCredentialEnvelope
{
private readonly object tokenCredential;
private readonly object tokenRequestContext;
/// <summary>
/// Create an instance of <see cref="ReflectionCredentialEnvelope"/>.
/// </summary>
/// <param name="tokenCredential">An instance of Azure.Core.TokenCredential.</param>
public ReflectionCredentialEnvelope(object tokenCredential)
{
this.tokenCredential = tokenCredential ?? throw new ArgumentNullException(nameof(tokenCredential));
if (tokenCredential.GetType().IsSubclassOf(Type.GetType("Azure.Core.TokenCredential, Azure.Core")))
{
this.tokenRequestContext = AzureCore.MakeTokenRequestContext(scopes: CredentialConstants.GetScopes());
}
else
{
throw new ArgumentException($"The provided {nameof(tokenCredential)} must inherit Azure.Core.TokenCredential", nameof(tokenCredential));
}
}
/// <summary>
/// Gets the TokenCredential object held by this class.
/// </summary>
public object Credential => this.tokenCredential;
/// <summary>
/// Gets an Azure.Core.AccessToken.
/// </summary>
/// <param name="cancellationToken">The System.Threading.CancellationToken to use.</param>
/// <returns>A valid Azure.Core.AccessToken.</returns>
public string GetToken(CancellationToken cancellationToken = default)
{
return AzureCore.InvokeGetToken(this.tokenCredential, this.tokenRequestContext, cancellationToken);
}
/// <summary>
/// Gets an Azure.Core.AccessToken.
/// </summary>
/// <param name="cancellationToken">The System.Threading.CancellationToken to use.</param>
/// <returns>A valid Azure.Core.AccessToken.</returns>
public Task<string> GetTokenAsync(CancellationToken cancellationToken = default)
{
return AzureCore.InvokeGetTokenAsync(this.tokenCredential, this.tokenRequestContext, cancellationToken);
}
/// <summary>
/// This class provides Reflection based wrappers around types found in the Azure.Core library.
/// Because of framework incompatibilities, we cannot take a direct reference on these types.
///
/// This class uses compiled Expression Trees. Read more here:
/// (https://docs.microsoft.com/dotnet/csharp/programming-guide/concepts/expression-trees/).
/// (https://docs.microsoft.com/dotnet/csharp/expression-trees).
/// </summary>
internal static class AzureCore
{
private static readonly Delegate GetTokenValue;
private static readonly Delegate GetTokenAsyncValue;
private static readonly Delegate GetTokenProperty;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1810:Initialize reference type static fields inline", Justification = "For both optimization and readability, I'm building these objects in the same method.")]
static AzureCore()
{
GetTokenValue = BuildDelegateGetToken();
var asyncDelegates = BuildDelegateGetTokenAsync();
GetTokenAsyncValue = asyncDelegates[0];
GetTokenProperty = asyncDelegates[1];
}
internal static string InvokeGetToken(object tokenCredential, object tokenRequestContext, CancellationToken cancellationToken)
{
return (string)GetTokenValue.DynamicInvoke(tokenCredential, tokenRequestContext, cancellationToken);
}
internal static async Task<string> InvokeGetTokenAsync(object tokenCredential, object tokenRequestContext, CancellationToken cancellationToken)
{
var task = (Task)GetTokenAsyncValue.DynamicInvoke(tokenCredential, tokenRequestContext, cancellationToken);
await task.ConfigureAwait(false);
return (string)GetTokenProperty.DynamicInvoke(task);
}
/// <summary>
/// This is a wrapper for the following constructor:
/// <code>public TokenRequestContext (string[] scopes, string? parentRequestId = default, string? claims = default);</code>
/// (https://docs.microsoft.com/dotnet/api/azure.core.tokenrequestcontext.-ctor).
/// </summary>
internal static object MakeTokenRequestContext(string[] scopes)
{
return Activator.CreateInstance(
type: Type.GetType("Azure.Core.TokenRequestContext, Azure.Core"),
args: new object[] { scopes, null, });
}
/// This creates a wrapper for the following method:
/// <code>public abstract Azure.Core.AccessToken GetToken (Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken).</code>
/// (https://docs.microsoft.com/dotnet/api/azure.core.tokencredential.gettoken).
private static Delegate BuildDelegateGetToken()
{
Type typeTokenCredential = Type.GetType("Azure.Core.TokenCredential, Azure.Core");
Type typeTokenRequestContext = Type.GetType("Azure.Core.TokenRequestContext, Azure.Core");
Type typeCancellationToken = typeof(CancellationToken);
var parameterExpression_tokenCredential = Expression.Parameter(type: typeTokenCredential, name: "parameterExpression_TokenCredential");
var parameterExpression_requestContext = Expression.Parameter(type: typeTokenRequestContext, name: "parameterExpression_RequestContext");
var parameterExpression_cancellationToken = Expression.Parameter(type: typeCancellationToken, name: "parameterExpression_CancellationToken");
var exprGetToken = Expression.Call(
instance: parameterExpression_tokenCredential,
method: typeTokenCredential.GetMethod(name: "GetToken", types: new Type[] { typeTokenRequestContext, typeCancellationToken }),
arg0: parameterExpression_requestContext,
arg1: parameterExpression_cancellationToken);
var exprTokenProperty = Expression.Property(
expression: exprGetToken,
propertyName: "Token");
return Expression.Lambda(
body: exprTokenProperty,
parameters: new ParameterExpression[]
{
parameterExpression_tokenCredential,
parameterExpression_requestContext,
parameterExpression_cancellationToken,
}).Compile();
}
/// <summary>
/// This is a wrapper for the following method:
/// <code>public abstract System.Threading.Tasks.ValueTask<Azure.Core.AccessToken> GetTokenAsync (Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken);</code>
/// (https://docs.microsoft.com/dotnet/api/azure.core.tokencredential.gettokenasync).
/// </summary>
/// <returns>
/// The Expression Tree library cannot handle async methods.
/// As a workaround, this method returns two Delegates.
/// First;
/// The first Delegate is a wrapper around GetTokenAsync which returns a ValueTask of AccessToken.
/// Then calls ValueTask.GetTask to convert that to a Task which is a known type for older frameworks.
/// This Task can be awaited.
/// Second;
/// The second Delegate is a wrapper around Task.Result which returns the AccessToken.
/// Then calls AccessToken.Token to get the string token.
/// </returns>
private static Delegate[] BuildDelegateGetTokenAsync()
{
Type typeTokenCredential = Type.GetType("Azure.Core.TokenCredential, Azure.Core");
Type typeTokenRequestContext = Type.GetType("Azure.Core.TokenRequestContext, Azure.Core");
Type typeCancellationToken = typeof(CancellationToken);
var parameterExpression_TokenCredential = Expression.Parameter(type: typeTokenCredential, name: "parameterExpression_TokenCredential");
var parameterExpression_RequestContext = Expression.Parameter(type: typeTokenRequestContext, name: "parameterExpression_RequestContext");
var parameterExpression_CancellationToken = Expression.Parameter(type: typeCancellationToken, name: "parameterExpression_CancellationToken");
// public abstract System.Threading.Tasks.ValueTask<Azure.Core.AccessToken> GetTokenAsync (Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken);
var methodInfo_GetTokenAsync = typeTokenCredential.GetMethod(name: "GetTokenAsync", types: new Type[] { typeTokenRequestContext, typeCancellationToken });
var exprGetTokenAsync = Expression.Call(
instance: parameterExpression_TokenCredential,
method: methodInfo_GetTokenAsync,
arg0: parameterExpression_RequestContext,
arg1: parameterExpression_CancellationToken);
var methodInfo_AsTask = methodInfo_GetTokenAsync.ReturnType.GetMethod("AsTask");
var exprAsTask = Expression.Call(
instance: exprGetTokenAsync,
method: methodInfo_AsTask);
var delegateGetTokenAsync = Expression.Lambda(
body: exprAsTask,
parameters: new ParameterExpression[]
{
parameterExpression_TokenCredential,
parameterExpression_RequestContext,
parameterExpression_CancellationToken,
}).Compile();
var parameterExpression_Task = Expression.Parameter(type: methodInfo_AsTask.ReturnType, name: "parameterExpression_Task");
var exprResultProperty = Expression.Property(
expression: parameterExpression_Task,
propertyName: "Result");
var exprTokenProperty = Expression.Property(
expression: exprResultProperty,
propertyName: "Token");
var delegateTokenProperty = Expression.Lambda(
body: exprTokenProperty,
parameters: new ParameterExpression[]
{
parameterExpression_Task,
}).Compile();
return new[] { delegateGetTokenAsync, delegateTokenProperty };
}
}
}
}