Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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
@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
Expand All @@ -15,6 +15,7 @@
using Microsoft.Identity.Client.Utils;
using Microsoft.Identity.Client.Extensibility;
using Microsoft.Identity.Client.OAuth2;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;
using System.Text;

Expand Down Expand Up @@ -98,18 +99,20 @@ public AcquireTokenForClientParameterBuilder WithSendX5C(bool withSendX5C)
/// <returns>The current instance of <see cref="AcquireTokenForClientParameterBuilder"/> to enable method chaining.</returns>
public AcquireTokenForClientParameterBuilder WithMtlsProofOfPossession()
{
if (ServiceBundle.Config.ClientCredential is not CertificateClientCredential certificateCredential)
if (ServiceBundle.Config.ClientCredential is CertificateClientCredential certificateCredential)
{
throw new MsalClientException(
if (certificateCredential.Certificate == null)
{
throw new MsalClientException(
MsalError.MtlsCertificateNotProvided,
MsalErrorMessage.MtlsCertificateNotProvidedMessage);
}
else
{
}

CommonParameters.AuthenticationOperation = new MtlsPopAuthenticationOperation(certificateCredential.Certificate);
CommonParameters.MtlsCertificate = certificateCredential.Certificate;
CommonParameters.MtlsCertificate = certificateCredential.Certificate;
}

CommonParameters.IsMtlsPopRequested = true;
return this;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@
// Licensed under the MIT License.

using System;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Identity.Client.ApiConfig.Parameters;
using Microsoft.Identity.Client.AuthScheme.PoP;
using Microsoft.Identity.Client.Instance.Discovery;
using Microsoft.Identity.Client.Instance.Validation;
using Microsoft.Identity.Client.Internal;
using Microsoft.Identity.Client.Internal.ClientCredential;
using Microsoft.Identity.Client.Internal.Requests;
using Microsoft.Identity.Client.ManagedIdentity;
using Microsoft.Identity.Client.Utils;
Expand Down Expand Up @@ -56,6 +59,9 @@ public async Task<AuthenticationResult> ExecuteAsync(
AcquireTokenForClientParameters clientParameters,
CancellationToken cancellationToken)
{
await commonParameters.ValidateAndWireMtlsPopAsync(ServiceBundle, cancellationToken)
.ConfigureAwait(false);

RequestContext requestContext = CreateRequestContextAndLogVersionInfo(commonParameters.CorrelationId, commonParameters.MtlsCertificate, cancellationToken);

AuthenticationRequestParameters requestParams = await _confidentialClientApplication.CreateRequestParametersAsync(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,12 @@
using Microsoft.Identity.Client.AppConfig;
using Microsoft.Identity.Client.AuthScheme;
using Microsoft.Identity.Client.AuthScheme.Bearer;
using Microsoft.Identity.Client.AuthScheme.PoP;
using Microsoft.Identity.Client.Extensibility;
using Microsoft.Identity.Client.Internal;
using Microsoft.Identity.Client.Internal.ClientCredential;
using Microsoft.Identity.Client.TelemetryCore.Internal.Events;
using Microsoft.Identity.Client.Utils;
using static Microsoft.Identity.Client.Extensibility.AbstractConfidentialClientAcquireTokenParameterBuilderExtension;

namespace Microsoft.Identity.Client.ApiConfig.Parameters
Expand All @@ -34,5 +38,75 @@ internal class AcquireTokenCommonParameters
public SortedList<string, Func<CancellationToken, Task<string>>> CacheKeyComponents { get; internal set; }
public string FmiPathSuffix { get; internal set; }
public string ClientAssertionFmiPath { get; internal set; }
public bool IsMtlsPopRequested { get; set; }

internal async Task ValidateAndWireMtlsPopAsync(IServiceBundle serviceBundle, CancellationToken ct)
{
if (!IsMtlsPopRequested)
{
return; // PoP not requested
}

// ────────────────────────────────────
// Case 1 – Certificate credential
// ────────────────────────────────────
if (serviceBundle.Config.ClientCredential is CertificateClientCredential certCred)
{
if (certCred.Certificate == null)
{
throw new MsalClientException(
MsalError.MtlsCertificateNotProvided,
MsalErrorMessage.MtlsCertificateNotProvidedMessage);
}

return;
}

// ────────────────────────────────────
// Case 2 – Client‑assertion delegate
// ────────────────────────────────────
if (serviceBundle.Config.ClientCredential is ClientAssertionDelegateCredential cadc)
{
var opts = new AssertionRequestOptions
{
ClientID = serviceBundle.Config.ClientId,
ClientCapabilities = serviceBundle.Config.ClientCapabilities,
Claims = Claims,
CancellationToken = ct
};

ClientAssertion ar = await cadc.GetAssertionAsync(opts, ct).ConfigureAwait(false);

if (ar.TokenBindingCertificate == null)
{
throw new MsalClientException(
MsalError.MtlsCertificateNotProvided,
MsalErrorMessage.MtlsCertificateNotProvidedMessage);
}

Wire(ar.TokenBindingCertificate, serviceBundle);
return;
}

// ────────────────────────────────────
// Case 3 – Any other credential (client‑secret etc.)
// ────────────────────────────────────
throw new MsalClientException(
MsalError.MtlsCertificateNotProvided,
MsalErrorMessage.MtlsCertificateNotProvidedMessage);
}

private void Wire(X509Certificate2 cert, IServiceBundle serviceBundle)
{
// region check (AAD only)
if (serviceBundle.Config.Authority.AuthorityInfo.AuthorityType == AuthorityType.Aad &&
serviceBundle.Config.AzureRegion == null)
{
throw new MsalClientException(MsalError.MtlsPopWithoutRegion, MsalErrorMessage.MtlsPopWithoutRegion);
}

AuthenticationOperation = new MtlsPopAuthenticationOperation(cert);
MtlsCertificate = cert;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System.Security.Cryptography.X509Certificates;

namespace Microsoft.Identity.Client
{
/// <summary>
/// Container returned from <c>WithClientAssertion</c>.
/// </summary>
public class ClientAssertion
{
/// <summary>
/// Represents the client assertion (JWT) and optional mutual‑TLS binding certificate returned
/// by the <c>clientAssertionProvider</c> callback supplied to
/// <see cref="ConfidentialClientApplicationBuilder.WithClientAssertion(System.Func{AssertionRequestOptions, System.Threading.CancellationToken, System.Threading.Tasks.Task{ClientAssertion}})"/>.
/// </summary>
/// <remarks>
/// MSAL forwards <see cref="Assertion"/> to the token endpoint as the <c>client_assertion</c> parameter.
/// When mutual‑TLS Proof‑of‑Possession (PoP) is enabled on the application and a
/// <see cref="TokenBindingCertificate"/> is provided, MSAL sets <c>client_assertion_type</c> to
/// <c>urn:ietf:params:oauth:client-assertion-type:jwt-pop</c>; otherwise it uses <c>jwt-bearer</c>.
/// <br/><br/>
/// Guidance on constructing the client assertion (required claims, audience, and lifetime) is available at
/// <see href="https://aka.ms/msal-net-client-assertion">aka.ms/msal-net-client-assertion</see>.
/// The assertion is created by your callback; MSAL does not modify or re‑sign it.
/// **Note:** It is up to the caller to cache the assertion and certificate if reuse is desired.
/// </remarks>
public string Assertion { get; set; }

/// <summary>
/// Optional. Certificate used to bind the client assertion for mutual‑TLS Proof‑of‑Possession (PoP).
/// </summary>
/// <remarks>
/// Provide a value only when PoP is enabled on the application. The certificate should include an
/// accessible private key. If <c>null</c>, MSAL treats the assertion as a bearer assertion and uses
/// <c>client_assertion_type=jwt-bearer</c>.
/// </remarks>
public X509Certificate2 TokenBindingCertificate { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -228,13 +228,12 @@ public ConfidentialClientApplicationBuilder WithClientAssertion(Func<string> cli
throw new ArgumentNullException(nameof(clientAssertionDelegate));
}

Func<CancellationToken, Task<string>> clientAssertionAsyncDelegate = (_) =>
{
return Task.FromResult(clientAssertionDelegate());
};

Config.ClientCredential = new SignedAssertionDelegateClientCredential(clientAssertionAsyncDelegate);
return this;
return WithClientAssertion(
(opts, ct) =>
Task.FromResult(new ClientAssertion
{
Assertion = clientAssertionDelegate() // bearer
}));
}

/// <summary>
Expand All @@ -252,8 +251,12 @@ public ConfidentialClientApplicationBuilder WithClientAssertion(Func<Cancellatio
throw new ArgumentNullException(nameof(clientAssertionAsyncDelegate));
}

Config.ClientCredential = new SignedAssertionDelegateClientCredential(clientAssertionAsyncDelegate);
return this;
return WithClientAssertion(
async (opts, ct) =>
{
string jwt = await clientAssertionAsyncDelegate(ct).ConfigureAwait(false);
return new ClientAssertion { Assertion = jwt }; // bearer
});
}

/// <summary>
Expand All @@ -270,7 +273,30 @@ public ConfidentialClientApplicationBuilder WithClientAssertion(Func<AssertionRe
throw new ArgumentNullException(nameof(clientAssertionAsyncDelegate));
}

Config.ClientCredential = new SignedAssertionDelegateClientCredential(clientAssertionAsyncDelegate);
return WithClientAssertion(
async (opts, _) =>
{
string jwt = await clientAssertionAsyncDelegate(opts).ConfigureAwait(false);
return new ClientAssertion { Assertion = jwt }; // bearer
});
}

/// <summary>
/// Configures the client application to use a client assertion for authentication.
/// </summary>
/// <remarks>This method allows the client application to authenticate using a custom client
/// assertion, which can be useful in scenarios where the assertion needs to be dynamically generated or
/// retrieved.</remarks>
/// <param name="clientAssertionProvider">A delegate that asynchronously provides an <see cref="ClientAssertion"/> based on the given <see
/// cref="AssertionRequestOptions"/> and <see cref="CancellationToken"/>. This delegate must not be <see
/// langword="null"/>.</param>
/// <returns>The <see cref="ConfidentialClientApplicationBuilder"/> instance configured with the specified client
/// assertion.</returns>
/// <exception cref="MsalClientException">Thrown if <paramref name="clientAssertionProvider"/> is <see langword="null"/>.</exception>
public ConfidentialClientApplicationBuilder WithClientAssertion(Func<AssertionRequestOptions,
CancellationToken, Task<ClientAssertion>> clientAssertionProvider)
{
Config.ClientCredential = new ClientAssertionDelegateCredential(clientAssertionProvider);
return this;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ internal class MtlsPopAuthenticationOperation : IAuthenticationOperation
public MtlsPopAuthenticationOperation(X509Certificate2 mtlsCert)
{
_mtlsCert = mtlsCert;
KeyId = ComputeX5tS256KeyId(_mtlsCert);
KeyId = CoreHelpers.ComputeX5tS256KeyId(_mtlsCert);
}

public int TelemetryTokenType => TelemetryTokenTypeConstants.MtlsPop;
Expand All @@ -40,20 +40,5 @@ public void FormatResult(AuthenticationResult authenticationResult)
{
authenticationResult.BindingCertificate = _mtlsCert;
}

private static string ComputeX5tS256KeyId(X509Certificate2 certificate)
{
// Extract the raw bytes of the certificate’s public key.
var publicKey = certificate.GetPublicKey();

// Compute the SHA-256 hash of the public key.
using (var sha256 = SHA256.Create())
{
byte[] hash = sha256.ComputeHash(publicKey);

// Return the hash encoded in Base64 URL format.
return Base64UrlHelpers.Encode(hash);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.AuthScheme.PoP;
using Microsoft.Identity.Client.Core;
using Microsoft.Identity.Client.Internal.Requests;
using Microsoft.Identity.Client.OAuth2;
using Microsoft.Identity.Client.PlatformsCommon.Interfaces;
using Microsoft.Identity.Client.TelemetryCore;

namespace Microsoft.Identity.Client.Internal.ClientCredential
{
/// <summary>
/// Handles client assertions supplied via a delegate that returns an
/// <see cref="ClientAssertion"/> (JWT + optional certificate bound for mTLS‑PoP).
/// </summary>
internal sealed class ClientAssertionDelegateCredential : IClientCredential
{
private readonly Func<AssertionRequestOptions, CancellationToken, Task<ClientAssertion>> _provider;

internal Task<ClientAssertion> GetAssertionAsync(
AssertionRequestOptions options,
CancellationToken cancellationToken) =>
_provider(options, cancellationToken);

public ClientAssertionDelegateCredential(
Func<AssertionRequestOptions, CancellationToken, Task<ClientAssertion>> provider)
{
_provider = provider ?? throw new ArgumentNullException(nameof(provider));
}

public AssertionType AssertionType => AssertionType.ClientAssertion;

// ──────────────────────────────────
// Main hook for token requests
// ──────────────────────────────────
public async Task AddConfidentialClientParametersAsync(
OAuth2Client oAuth2Client,
AuthenticationRequestParameters p,
ICryptographyManager _,
string tokenEndpoint,
CancellationToken ct)
{
var opts = new AssertionRequestOptions
{
CancellationToken = ct,
ClientID = p.AppConfig.ClientId,
TokenEndpoint = tokenEndpoint,
ClientCapabilities = p.RequestContext.ServiceBundle.Config.ClientCapabilities,
Claims = p.Claims,
ClientAssertionFmiPath = p.ClientAssertionFmiPath
};

ClientAssertion resp = await _provider(opts, ct).ConfigureAwait(false);

if (string.IsNullOrWhiteSpace(resp?.Assertion))
{
throw new MsalClientException(MsalError.InvalidClientAssertion,
MsalErrorMessage.InvalidClientAssertionEmpty);
}

// Decide bearer vs mTLS PoP
bool IsMtlsPopRequested = p.IsMtlsPopRequested;

if (IsMtlsPopRequested && resp.TokenBindingCertificate != null)
{
oAuth2Client.AddBodyParameter(
OAuth2Parameter.ClientAssertionType,
OAuth2AssertionType.JwtPop /* constant added in OAuth2AssertionType */);
}
else
{
oAuth2Client.AddBodyParameter(
OAuth2Parameter.ClientAssertionType,
OAuth2AssertionType.JwtBearer);
}

oAuth2Client.AddBodyParameter(OAuth2Parameter.ClientAssertion, resp.Assertion);
}
}
}
Loading
Loading