/
ClientCertificateCredential.cs
227 lines (201 loc) · 12.5 KB
/
ClientCertificateCredential.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
217
218
219
220
221
222
223
224
225
226
227
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Azure.Core;
using Azure.Core.Pipeline;
using Microsoft.Identity.Client;
using System;
using System.ComponentModel;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
namespace Azure.Identity
{
/// <summary>
/// Enables authentication of a service principal to Microsoft Entra ID using a X509 certificate that is assigned to its App Registration. More information
/// on how to configure certificate authentication can be found at
/// <see href="https://learn.microsoft.com/entra/identity-platform/certificate-credentials#register-your-certificate-with-microsoft-identity-platform"/>.
/// </summary>
public class ClientCertificateCredential : TokenCredential
{
internal const string Troubleshooting = "See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/clientcertificatecredential/troubleshoot";
/// <summary>
/// Gets the Microsoft Entra tenant (directory) ID of the service principal
/// </summary>
internal string TenantId { get; }
/// <summary>
/// Gets the client (application) ID of the service principal
/// </summary>
internal string ClientId { get; }
internal IX509Certificate2Provider ClientCertificateProvider { get; }
internal MsalConfidentialClient Client { get; }
private readonly CredentialPipeline _pipeline;
internal readonly string[] AdditionallyAllowedTenantIds;
internal TenantIdResolverBase TenantIdResolver { get; }
/// <summary>
/// Protected constructor for mocking.
/// </summary>
protected ClientCertificateCredential()
{ }
/// <summary>
/// Creates an instance of the ClientCertificateCredential with the details needed to authenticate against Microsoft Entra ID with the specified certificate.
/// </summary>
/// <param name="tenantId">The Microsoft Entra tenant (directory) ID of the service principal.</param>
/// <param name="clientId">The client (application) ID of the service principal</param>
/// <param name="clientCertificatePath">The path to a file which contains both the client certificate and private key.</param>
public ClientCertificateCredential(string tenantId, string clientId, string clientCertificatePath)
: this(tenantId, clientId, clientCertificatePath, null, null, null, null)
{ }
/// <summary>
/// Creates an instance of the ClientCertificateCredential with the details needed to authenticate against Microsoft Entra ID with the specified certificate.
/// </summary>
/// <param name="tenantId">The Microsoft Entra tenant (directory) ID of the service principal.</param>
/// <param name="clientId">The client (application) ID of the service principal</param>
/// <param name="clientCertificatePath">The path to a file which contains both the client certificate and private key.</param>
/// <param name="options">Options that allow to configure the management of the requests sent to Microsoft Entra ID.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
public ClientCertificateCredential(string tenantId, string clientId, string clientCertificatePath, TokenCredentialOptions options)
: this(tenantId, clientId, clientCertificatePath, null, options, null, null)
{ }
/// <summary>
/// Creates an instance of the ClientCertificateCredential with the details needed to authenticate against Microsoft Entra ID with the specified certificate.
/// </summary>
/// <param name="tenantId">The Microsoft Entra tenant (directory) ID of the service principal.</param>
/// <param name="clientId">The client (application) ID of the service principal</param>
/// <param name="clientCertificatePath">The path to a file which contains both the client certificate and private key.</param>
/// <param name="options">Options that allow to configure the management of the requests sent to Microsoft Entra ID.</param>
public ClientCertificateCredential(string tenantId, string clientId, string clientCertificatePath, ClientCertificateCredentialOptions options)
: this(tenantId, clientId, clientCertificatePath, null, options, null, null)
{ }
/// <summary>
/// Creates an instance of the ClientCertificateCredential with the details needed to authenticate against Microsoft Entra ID with the specified certificate.
/// </summary>
/// <param name="tenantId">The Microsoft Entra tenant (directory) ID of the service principal.</param>
/// <param name="clientId">The client (application) ID of the service principal</param>
/// <param name="clientCertificate">The authentication X509 Certificate of the service principal</param>
public ClientCertificateCredential(string tenantId, string clientId, X509Certificate2 clientCertificate)
: this(tenantId, clientId, clientCertificate, null, null, null)
{ }
/// <summary>
/// Creates an instance of the ClientCertificateCredential with the details needed to authenticate against Microsoft Entra ID with the specified certificate.
/// </summary>
/// <param name="tenantId">The Microsoft Entra tenant (directory) ID of the service principal.</param>
/// <param name="clientId">The client (application) ID of the service principal</param>
/// <param name="clientCertificate">The authentication X509 Certificate of the service principal</param>
/// <param name="options">Options that allow to configure the management of the requests sent to Microsoft Entra ID.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
public ClientCertificateCredential(string tenantId, string clientId, X509Certificate2 clientCertificate, TokenCredentialOptions options)
: this(tenantId, clientId, clientCertificate, options, null, null)
{ }
/// <summary>
/// Creates an instance of the ClientCertificateCredential with the details needed to authenticate against Microsoft Entra ID with the specified certificate.
/// </summary>
/// <param name="tenantId">The Microsoft Entra tenant (directory) ID of the service principal.</param>
/// <param name="clientId">The client (application) ID of the service principal</param>
/// <param name="clientCertificate">The authentication X509 Certificate of the service principal</param>
/// <param name="options">Options that allow to configure the management of the requests sent to Microsoft Entra ID.</param>
public ClientCertificateCredential(string tenantId, string clientId, X509Certificate2 clientCertificate, ClientCertificateCredentialOptions options)
: this(tenantId, clientId, clientCertificate, options, null, null)
{ }
internal ClientCertificateCredential(
string tenantId,
string clientId,
string certificatePath,
string certificatePassword,
TokenCredentialOptions options,
CredentialPipeline pipeline,
MsalConfidentialClient client)
: this(
tenantId,
clientId,
new X509Certificate2FromFileProvider(certificatePath ?? throw new ArgumentNullException(nameof(certificatePath)), certificatePassword),
options,
pipeline,
client)
{ }
internal ClientCertificateCredential(
string tenantId,
string clientId,
X509Certificate2 certificate,
TokenCredentialOptions options,
CredentialPipeline pipeline,
MsalConfidentialClient client)
: this(
tenantId,
clientId,
new X509Certificate2FromObjectProvider(certificate ?? throw new ArgumentNullException(nameof(certificate))),
options,
pipeline,
client)
{ }
internal ClientCertificateCredential(
string tenantId,
string clientId,
IX509Certificate2Provider certificateProvider,
TokenCredentialOptions options,
CredentialPipeline pipeline,
MsalConfidentialClient client)
{
TenantId = Validations.ValidateTenantId(tenantId, nameof(tenantId));
ClientId = clientId ?? throw new ArgumentNullException(nameof(clientId));
ClientCertificateProvider = certificateProvider;
_pipeline = pipeline ?? CredentialPipeline.GetInstance(options);
ClientCertificateCredentialOptions certCredOptions = options as ClientCertificateCredentialOptions;
Client = client ??
new MsalConfidentialClient(
_pipeline,
tenantId,
clientId,
certificateProvider,
certCredOptions?.SendCertificateChain ?? false,
options);
TenantIdResolver = options?.TenantIdResolver ?? TenantIdResolverBase.Default;
AdditionallyAllowedTenantIds = TenantIdResolver.ResolveAddionallyAllowedTenantIds((options as ISupportsAdditionallyAllowedTenants)?.AdditionallyAllowedTenants);
}
/// <summary>
/// Obtains a token from Microsoft Entra ID, using the specified X509 certificate to authenticate. Acquired tokens are
/// cached by the credential instance. Token lifetime and refreshing is handled automatically. Where possible, reuse credential
/// instances to optimize cache effectiveness.
/// </summary>
/// <param name="requestContext">The details of the authentication request.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>An <see cref="AccessToken"/> which can be used to authenticate service client calls.</returns>
public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken = default)
{
using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope("ClientCertificateCredential.GetToken", requestContext);
try
{
var tenantId = TenantIdResolver.Resolve(TenantId, requestContext, AdditionallyAllowedTenantIds);
AuthenticationResult result = Client.AcquireTokenForClientAsync(requestContext.Scopes, tenantId, requestContext.Claims, requestContext.IsCaeEnabled, false, cancellationToken).EnsureCompleted();
return scope.Succeeded(new AccessToken(result.AccessToken, result.ExpiresOn));
}
catch (Exception e)
{
throw scope.FailWrapAndThrow(e, Troubleshooting);
}
}
/// <summary>
/// Obtains a token from Microsoft Entra ID, using the specified X509 certificate to authenticate. Acquired tokens are
/// cached by the credential instance. Token lifetime and refreshing is handled automatically. Where possible, reuse credential
/// instances to optimize cache effectiveness.
/// </summary>
/// <param name="requestContext">The details of the authentication request.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>An <see cref="AccessToken"/> which can be used to authenticate service client calls.</returns>
public override async ValueTask<AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken = default)
{
using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope("ClientCertificateCredential.GetToken", requestContext);
try
{
var tenantId = TenantIdResolver.Resolve(TenantId, requestContext, AdditionallyAllowedTenantIds);
AuthenticationResult result = await Client
.AcquireTokenForClientAsync(requestContext.Scopes, tenantId, requestContext.Claims, requestContext.IsCaeEnabled, true, cancellationToken)
.ConfigureAwait(false);
return scope.Succeeded(new AccessToken(result.AccessToken, result.ExpiresOn));
}
catch (Exception e)
{
throw scope.FailWrapAndThrow(e);
}
}
}
}