Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,17 @@ internal static AcquireTokenForClientParameterBuilder Create(
IConfidentialClientApplicationExecutor confidentialClientApplicationExecutor,
IEnumerable<string> scopes)
{
return new AcquireTokenForClientParameterBuilder(confidentialClientApplicationExecutor).WithScopes(scopes);
var builder = new AcquireTokenForClientParameterBuilder(confidentialClientApplicationExecutor).WithScopes(scopes);

if (!string.IsNullOrEmpty(confidentialClientApplicationExecutor.ServiceBundle.Config.CertificateSerialNumber))
{
builder.WithAdditionalCacheKeyComponents(new SortedList<string, string>
{
{ Constants.CertSerialNumber, confidentialClientApplicationExecutor.ServiceBundle.Config.CertificateSerialNumber }
});
}

return builder;
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ public string ClientVersion
public bool IsManagedIdentity { get; }
public bool IsConfidentialClient { get; }
public bool IsPublicClient => !IsConfidentialClient && !IsManagedIdentity;
public string CertificateSerialNumber { get; internal set; }

public Func<AppTokenProviderParameters, Task<AppTokenProviderResult>> AppTokenProvider;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,34 @@ public ConfidentialClientApplicationBuilder WithCertificate(X509Certificate2 cer
return this;
}

/// <summary>
/// Sets the certificate associated with the application.
/// Applicable to first-party applications only, this method also allows to specify
/// if the <see href="https://datatracker.ietf.org/doc/html/rfc7517#section-4.7">x5c claim</see> should be sent to Azure AD.
/// Sending the x5c enables application developers to achieve easy certificate roll-over in Azure AD:
/// this method will send the certificate chain to Azure AD along with the token request,
/// so that Azure AD can use it to validate the subject name based on a trusted issuer policy.
/// This saves the application admin from the need to explicitly manage the certificate rollover
/// (either via portal or PowerShell/CLI operation). For details see https://aka.ms/msal-net-sni
/// This api allow you to associate the tokens acquired from Azure AD with the certificate serial number.
/// This can be used to partition the cache by certificate. Tokens acquired with one certificate will not be available to another certificate with a different serial number.
/// </summary>
/// <param name="certificate">The X509 certificate used as credentials to prove the identity of the application to Azure AD.</param>
/// <param name="sendX5C">To send X5C with every request or not. The default is <c>false</c></param>
/// <param name="associateTokensWithCertificateSerialNumber">Determines if the application tokens acquired from Azure AD are associated with the certificate serial number</param>
/// <remarks>You should use certificates with a private key size of at least 2048 bytes. Future versions of this library might reject certificates with smaller keys. </remarks>
public ConfidentialClientApplicationBuilder WithCertificate(X509Certificate2 certificate, bool sendX5C, bool associateTokensWithCertificateSerialNumber)
{
if (associateTokensWithCertificateSerialNumber)
{
Config.CertificateSerialNumber = certificate.SerialNumber;
}

WithCertificate(certificate, sendX5C);

return this;
}

/// <summary>
/// Sets the certificate associated with the application along with the specific claims to sign.
/// By default, this will merge the <paramref name="claimsToSign"/> with the default required set of claims needed for authentication.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ internal static class Constants
public const string ManagedIdentityDefaultClientId = "system_assigned_managed_identity";
public const string ManagedIdentityDefaultTenant = "managed_identity";
public const string CiamAuthorityHostSuffix = ".ciamlogin.com";
public const string CertSerialNumber = "cert_sn";

public const int CallerSdkIdMaxLength = 10;
public const int CallerSdkVersionMaxLength = 20;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
Microsoft.Identity.Client.AssertionRequestOptions.ClientCapabilities.get -> System.Collections.Generic.IEnumerable<string>
Microsoft.Identity.Client.AssertionRequestOptions.ClientCapabilities.set -> void
Microsoft.Identity.Client.AssertionRequestOptions.ClientCapabilities.set -> void
Microsoft.Identity.Client.ConfidentialClientApplicationBuilder.WithCertificate(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate, bool sendX5C, bool associateTokensWithCertificateSerialNumber) -> Microsoft.Identity.Client.ConfidentialClientApplicationBuilder
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
Microsoft.Identity.Client.AssertionRequestOptions.ClientCapabilities.get -> System.Collections.Generic.IEnumerable<string>
Microsoft.Identity.Client.AssertionRequestOptions.ClientCapabilities.set -> void
Microsoft.Identity.Client.ConfidentialClientApplicationBuilder.WithCertificate(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate, bool sendX5C, bool associateTokensWithCertificateSerialNumber) -> Microsoft.Identity.Client.ConfidentialClientApplicationBuilder
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
Microsoft.Identity.Client.AssertionRequestOptions.ClientCapabilities.get -> System.Collections.Generic.IEnumerable<string>
Microsoft.Identity.Client.AssertionRequestOptions.ClientCapabilities.set -> void
Microsoft.Identity.Client.ConfidentialClientApplicationBuilder.WithCertificate(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate, bool sendX5C, bool associateTokensWithCertificateSerialNumber) -> Microsoft.Identity.Client.ConfidentialClientApplicationBuilder
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
Microsoft.Identity.Client.AssertionRequestOptions.ClientCapabilities.get -> System.Collections.Generic.IEnumerable<string>
Microsoft.Identity.Client.AssertionRequestOptions.ClientCapabilities.set -> void
Microsoft.Identity.Client.ConfidentialClientApplicationBuilder.WithCertificate(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate, bool sendX5C, bool associateTokensWithCertificateSerialNumber) -> Microsoft.Identity.Client.ConfidentialClientApplicationBuilder
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
Microsoft.Identity.Client.AssertionRequestOptions.ClientCapabilities.get -> System.Collections.Generic.IEnumerable<string>
Microsoft.Identity.Client.AssertionRequestOptions.ClientCapabilities.set -> void
Microsoft.Identity.Client.ConfidentialClientApplicationBuilder.WithCertificate(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate, bool sendX5C, bool associateTokensWithCertificateSerialNumber) -> Microsoft.Identity.Client.ConfidentialClientApplicationBuilder
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
Microsoft.Identity.Client.AssertionRequestOptions.ClientCapabilities.get -> System.Collections.Generic.IEnumerable<string>
Microsoft.Identity.Client.AssertionRequestOptions.ClientCapabilities.set -> void
Microsoft.Identity.Client.ConfidentialClientApplicationBuilder.WithCertificate(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate, bool sendX5C, bool associateTokensWithCertificateSerialNumber) -> Microsoft.Identity.Client.ConfidentialClientApplicationBuilder
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ namespace Microsoft.Identity.Test.Unit
[DeploymentItem(@"Resources\RSATestCertDotNet.pfx")]
public class ConfidentialClientWithCertTests : TestBase
{
private byte[] _serializedCache;

[TestInitialize]
public override void TestInitialize()
{
Expand Down Expand Up @@ -704,6 +706,92 @@ public async Task RopcCcaSendsX5CAsync(bool sendX5C)
}
}

[TestMethod]
public async Task EnsureCertificateSerialNumberIsAddedToCacheKeyTestAsync()
{
using (var httpManager = new MockHttpManager())
{
var certificate = CertHelper.GetOrCreateTestCert();

var app = ConfidentialClientApplicationBuilder.Create(TestConstants.ClientId)
.WithAuthority(new Uri(ClientApplicationBase.DefaultAuthority), true)
.WithRedirectUri(TestConstants.RedirectUri)
.WithCertificate(certificate, true, true)
.WithHttpManager(httpManager)
.WithExperimentalFeatures()
.BuildConcrete();

var appCacheAccess = app.AppTokenCache.RecordAccess();

app.AppTokenCache.SetBeforeAccess(BeforeCacheAccess);
app.AppTokenCache.SetAfterAccess(AfterCacheAccess);

httpManager.AddInstanceDiscoveryMockHandler();
httpManager.AddMockHandlerSuccessfulClientCredentialTokenResponseMessage();

//Ensure serial number matches
var result = await app.AcquireTokenForClient(TestConstants.s_scope.ToArray())
.ExecuteAsync(CancellationToken.None)
.ConfigureAwait(false);

Assert.IsNotNull(result);
Assert.AreEqual(TokenSource.IdentityProvider, result.AuthenticationResultMetadata.TokenSource);
Assert.AreEqual("header.payload.signature", result.AccessToken);

var serialNumber = app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().First().AdditionalCacheKeyComponents.FirstOrDefault().Value;
Assert.AreEqual(certificate.SerialNumber, serialNumber);

//Ensure serial number is available from cache

result = await app.AcquireTokenForClient(TestConstants.s_scope.ToArray())
.ExecuteAsync(CancellationToken.None)
.ConfigureAwait(false);

Assert.IsNotNull(result);
Assert.AreEqual(TokenSource.Cache, result.AuthenticationResultMetadata.TokenSource);
Assert.AreEqual("header.payload.signature", result.AccessToken);

serialNumber = app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().First().AdditionalCacheKeyComponents.FirstOrDefault().Value;
Assert.AreEqual(certificate.SerialNumber, serialNumber);

//Ensure serial number is available from cache in new app
var app2 = ConfidentialClientApplicationBuilder.Create(TestConstants.ClientId)
.WithAuthority(new Uri(ClientApplicationBase.DefaultAuthority), true)
.WithRedirectUri(TestConstants.RedirectUri)
.WithCertificate(certificate, true, true)
.WithHttpManager(httpManager)
.WithExperimentalFeatures()
.BuildConcrete();

appCacheAccess = app2.AppTokenCache.RecordAccess();

app2.AppTokenCache.SetBeforeAccess(BeforeCacheAccess);
app2.AppTokenCache.SetAfterAccess(AfterCacheAccess);

//Ensure serial number matches
result = await app2.AcquireTokenForClient(TestConstants.s_scope.ToArray())
.ExecuteAsync(CancellationToken.None)
.ConfigureAwait(false);

Assert.IsNotNull(result);
Assert.AreEqual(TokenSource.Cache, result.AuthenticationResultMetadata.TokenSource);
Assert.AreEqual("header.payload.signature", result.AccessToken);

serialNumber = app.AppTokenCacheInternal.Accessor.GetAllAccessTokens().First().AdditionalCacheKeyComponents.FirstOrDefault().Value;
Assert.AreEqual(certificate.SerialNumber, serialNumber);
}
}

private void BeforeCacheAccess(TokenCacheNotificationArgs args)
{
args.TokenCache.DeserializeMsalV3(_serializedCache);
}

private void AfterCacheAccess(TokenCacheNotificationArgs args)
{
_serializedCache = args.TokenCache.SerializeMsalV3();
}

private static string ComputeCertThumbprint(X509Certificate2 certificate, bool useSha2)
{
string thumbprint = null;
Expand Down
Loading