/
ClientAssertionCredential.cs
123 lines (105 loc) · 7.04 KB
/
ClientAssertionCredential.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Pipeline;
using Microsoft.Identity.Client;
namespace Azure.Identity
{
/// <summary>
/// Enables authentication of a Microsoft Entra service principal using a signed client assertion.
/// </summary>
public class ClientAssertionCredential : TokenCredential
{
internal readonly string[] AdditionallyAllowedTenantIds;
internal string TenantId { get; }
internal string ClientId { get; }
internal MsalConfidentialClient Client { get; }
internal CredentialPipeline Pipeline { get; }
internal bool AllowMultiTenantAuthentication { get; }
internal TenantIdResolverBase TenantIdResolver { get; }
/// <summary>
/// Protected constructor for mocking.
/// </summary>
protected ClientAssertionCredential()
{ }
/// <summary>
/// Creates an instance of the ClientCertificateCredential with an asynchronous callback that provides a signed client assertion to authenticate against Microsoft Entra ID.
/// </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="assertionCallback">An asynchronous callback returning a valid client assertion used to authenticate the service principal.</param>
/// <param name="options">Options that allow to configure the management of the requests sent to Microsoft Entra ID.</param>
public ClientAssertionCredential(string tenantId, string clientId, Func<CancellationToken, Task<string>> assertionCallback, ClientAssertionCredentialOptions options = default)
{
Argument.AssertNotNull(clientId, nameof(clientId));
TenantId = Validations.ValidateTenantId(tenantId, nameof(tenantId));
ClientId = clientId;
Client = options?.MsalClient ?? new MsalConfidentialClient(options?.Pipeline ?? CredentialPipeline.GetInstance(options), tenantId, clientId, assertionCallback, options);
Pipeline = options?.Pipeline ?? options?.Pipeline ?? CredentialPipeline.GetInstance(options);
TenantIdResolver = options?.TenantIdResolver ?? TenantIdResolverBase.Default;
AdditionallyAllowedTenantIds = TenantIdResolver.ResolveAddionallyAllowedTenantIds((options as ISupportsAdditionallyAllowedTenants)?.AdditionallyAllowedTenants);
}
/// <summary>
/// Creates an instance of the ClientCertificateCredential with a synchronous callback that provides a signed client assertion to authenticate against Microsoft Entra ID.
/// </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="assertionCallback">A synchronous callback returning a valid client assertion used to authenticate the service principal.</param>
/// <param name="options">Options that allow to configure the management of the requests sent to Microsoft Entra ID.</param>
public ClientAssertionCredential(string tenantId, string clientId, Func<string> assertionCallback, ClientAssertionCredentialOptions options = default)
{
Argument.AssertNotNull(clientId, nameof(clientId));
TenantId = Validations.ValidateTenantId(tenantId, nameof(tenantId));
ClientId = clientId;
Client = options?.MsalClient ?? new MsalConfidentialClient(options?.Pipeline ?? CredentialPipeline.GetInstance(options), tenantId, clientId, assertionCallback, options);
Pipeline = options?.Pipeline ?? options?.Pipeline ?? CredentialPipeline.GetInstance(options);
TenantIdResolver = options?.TenantIdResolver ?? TenantIdResolverBase.Default;
AdditionallyAllowedTenantIds = TenantIdResolver.ResolveAddionallyAllowedTenantIds((options as ISupportsAdditionallyAllowedTenants)?.AdditionallyAllowedTenants);
}
/// <summary>
/// Obtains a token from Microsoft Entra ID, by calling the assertionCallback specified when constructing the credential to obtain a client assertion for authentication.
/// </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("ClientAssertionCredential.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);
}
}
/// <summary>
/// Obtains a token from Microsoft Entra ID, by calling the assertionCallback specified when constructing the credential to obtain a client assertion for authentication.
/// </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 async override ValueTask<AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken = default)
{
using CredentialDiagnosticScope scope = Pipeline.StartGetTokenScope("ClientAssertionCredential.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);
}
}
}
}