Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@
<MicrosoftGraphVersion>4.34.0</MicrosoftGraphVersion>
<MicrosoftGraphBetaVersion>4.50.0-preview</MicrosoftGraphBetaVersion>
<MicrosoftExtensionsHttpVersion>3.1.3</MicrosoftExtensionsHttpVersion>
<MicrosoftIdentityAbstractions>2.0.1</MicrosoftIdentityAbstractions>
<MicrosoftIdentityAbstractions>2.1.0</MicrosoftIdentityAbstractions>
<!--CVE-2021-24112-->
<SystemDrawingCommon>4.7.2</SystemDrawingCommon>
</PropertyGroup>
Expand Down
11 changes: 7 additions & 4 deletions Microsoft.Identity.Web.sln
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,6 @@ EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PerformanceTestService", "tests\PerformanceTests\PerformanceTestService\PerformanceTestService.csproj", "{AA1F64B8-EFA8-4000-9B91-A8B0D50A5D0E}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "IntegrationTests", "IntegrationTests", "{A7B1AE31-4E89-42A0-8264-FBEA795AB7D2}"
ProjectSection(SolutionItems) = preProject
tests\IntegrationTests\Directory.Build.props = tests\IntegrationTests\Directory.Build.props
tests\IntegrationTests\TokenAcquirerTests\TokenAcquirerTests.csproj = tests\IntegrationTests\TokenAcquirerTests\TokenAcquirerTests.csproj
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebAppUiTests", "tests\IntegrationTests\WebAppUiTests\WebAppUiTests.csproj", "{ECDE3310-9548-491F-A0C6-8F086E0579D3}"
EndProject
Expand Down Expand Up @@ -166,6 +162,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MinimalWebApi", "tests\DevA
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DaemonConsoleCallingDownstreamApi", "tests\DevApps\daemon-app\daemon-console-calling-downstreamApi\DaemonConsoleCallingDownstreamApi.csproj", "{5DE68949-118E-4A2E-A541-8FB5CA030CD6}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TokenAcquirerTests", "tests\IntegrationTests\TokenAcquirerTests\TokenAcquirerTests.csproj", "{AB8177BE-8961-4698-B064-42943885D48D}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -371,6 +369,10 @@ Global
{5DE68949-118E-4A2E-A541-8FB5CA030CD6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5DE68949-118E-4A2E-A541-8FB5CA030CD6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5DE68949-118E-4A2E-A541-8FB5CA030CD6}.Release|Any CPU.Build.0 = Release|Any CPU
{AB8177BE-8961-4698-B064-42943885D48D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AB8177BE-8961-4698-B064-42943885D48D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AB8177BE-8961-4698-B064-42943885D48D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AB8177BE-8961-4698-B064-42943885D48D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -445,6 +447,7 @@ Global
{30CFD8F7-8B85-4433-8EDB-A644FCE28804} = {E37CDBC1-18F6-4C06-A3EE-532C9106721F}
{D12AF43A-72EC-4459-B6F4-0755190D9222} = {E37CDBC1-18F6-4C06-A3EE-532C9106721F}
{5DE68949-118E-4A2E-A541-8FB5CA030CD6} = {E37CDBC1-18F6-4C06-A3EE-532C9106721F}
{AB8177BE-8961-4698-B064-42943885D48D} = {A7B1AE31-4E89-42A0-8264-FBEA795AB7D2}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {104367F1-CE75-4F40-B32F-F14853973187}
Expand Down
67 changes: 67 additions & 0 deletions src/Microsoft.Identity.Web.TokenAcquisition/MsAuth10AtPop.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.Extensibility;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;

namespace Microsoft.Identity.Web
{
internal static class MsAuth10AtPop
{
public static AcquireTokenForClientParameterBuilder WithAtPop(
this AcquireTokenForClientParameterBuilder builder,
X509Certificate2 clientCertificate,
string popPublicKey,
string jwkClaim,
string clientId)
{
builder.WithProofOfPosessionKeyId(popPublicKey);
builder.OnBeforeTokenRequest((data) =>
{
string? signedAssertion = GetSignedClientAssertion(
clientCertificate,
data.RequestUri.AbsoluteUri,
jwkClaim,
clientId);

data.BodyParameters.Remove("client_assertion");
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bgavrilMS
Would it be possible, when we use builder.WithProofOfPosessionKeyId(popPublicKey) that MSAL does not compute the signed assertion? (as it's not necessary)
I can create a GitHub issue in the MSAL.NET repo if you agree.

data.BodyParameters.Add("request", signedAssertion);
return Task.CompletedTask;
});

return builder;
}

private static string? GetSignedClientAssertion(
X509Certificate2 certificate,
string audience,
string jwkClaim,
string clientId)
{
// no need to add exp, nbf as JsonWebTokenHandler will add them by default
var claims = new Dictionary<string, object>()
{
{ "aud", audience },
{ "iss", clientId },
{ "jti", Guid.NewGuid().ToString() },
{ "sub", clientId },
{ "pop_jwk", jwkClaim }
};

var securityTokenDescriptor = new SecurityTokenDescriptor
{
Claims = claims,
SigningCredentials = new X509SigningCredentials(certificate)
};

var handler = new JsonWebTokenHandler();
return handler.CreateToken(securityTokenDescriptor);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ async Task<AcquireTokenResult> ITokenAcquirer.GetTokenForAppAsync(string scope,
Tenant = tokenAcquisitionOptions.Tenant,
UserFlow = tokenAcquisitionOptions.UserFlow,
PopPublicKey = tokenAcquisitionOptions.PopPublicKey,
JwkClaim = tokenAcquisitionOptions.JwkClaim,
};
}
}
Expand Down
25 changes: 18 additions & 7 deletions src/Microsoft.Identity.Web.TokenAcquisition/TokenAcquisition.cs
Original file line number Diff line number Diff line change
Expand Up @@ -370,15 +370,26 @@ public Task<AuthenticationResult> GetAuthenticationResultForAppAsync(
{
builder.WithProofOfPossession(tokenAcquisitionOptions.PoPConfiguration);
}
if (tokenAcquisitionOptions.PopPublicKey != null)
if (!string.IsNullOrEmpty(tokenAcquisitionOptions.PopPublicKey))
{
builder.WithProofOfPosessionKeyId(tokenAcquisitionOptions.PopPublicKey, "pop");
builder.OnBeforeTokenRequest((data) =>
if (string.IsNullOrEmpty(tokenAcquisitionOptions.JwkClaim))
{
data.BodyParameters.Add("req_cnf", tokenAcquisitionOptions.PopPublicKey);
data.BodyParameters.Add("token_type", "pop");
return Task.CompletedTask;
});
builder.WithProofOfPosessionKeyId(tokenAcquisitionOptions.PopPublicKey, "pop");
builder.OnBeforeTokenRequest((data) =>
Copy link
Member

@bgavrilMS bgavrilMS Mar 13, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess this is "new POP" as defined by ESTS (as opposed to MsAuth10ATPOP)? I would add some comments here to make it clear.

Not critical: For "new POP" I would recommend that you use MSAL's higher level API WithProofOfPossession(config). Since you won't be letting MSAL generate the SHR, you can do this:

class CryptoProvider :  IPoPCryptoProvider 
{
      string CannonicalPublicKeyJwk { get; } => JwkClaim;
      string CryptographicAlgorithm { get; } => "RS256";  // RSA only
      public byte[] Sign(byte[] data) 
      { 
          throw new NotImplementedException(); // Wilson will generate the SHR
      }
}

PoPAuthenticationConfiguration config = new PoPAuthenticationConfiguration();
config.CryptoProvider = new CryptoProvider();
builder.WithProofOfPossesion(config);

Note that this implies that MSAL computes the key id based on the JWK, i.e. kid=hash(JWK). If you want to support JWK and kid provided by user, I think the code that you wrote is the way to go.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also note that this is RSA only. If you need to support other algorithms such as ECD, we need to run a small test to see if another param needs to be exposed or not. In MSAL we decided to expose CryptographicAlgorithm but I don't know if this is needed when Wilson creates the SHR.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also happy to hear how we can re-design the PoPAuthenticationConfiguration interface. The original design did not take into account Wilson creating the SHR. It works, but it's clunky...

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jmprieur said you synced off-line and are okay with this proposal, is that right?

{
data.BodyParameters.Add("req_cnf", tokenAcquisitionOptions.PopPublicKey);
data.BodyParameters.Add("token_type", "pop");
return Task.CompletedTask;
});
}
else
{
builder.WithAtPop(
application.AppConfig.ClientCredentialCertificate,
tokenAcquisitionOptions.PopPublicKey,
tokenAcquisitionOptions.JwkClaim,
application.AppConfig.ClientId);
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ public class TokenAcquisitionOptions : AcquireTokenOptions
Claims = Claims,
PoPConfiguration = PoPConfiguration,
PopPublicKey = PopPublicKey,
JwkClaim = JwkClaim,
CancellationToken = CancellationToken,
LongRunningWebApiSessionKey = LongRunningWebApiSessionKey,
};
Expand Down
68 changes: 66 additions & 2 deletions tests/IntegrationTests/TokenAcquirerTests/TokenAcquirer.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
Expand Down Expand Up @@ -144,6 +146,70 @@ public async Task AcquireTokenWithPop_ClientCredentialsAsync()
Assert.NotNull(result.AccessToken);
}

[IgnoreOnAzureDevopsFact]
//[Fact]
public async Task AcquireTokenWithMs10AtPop_ClientCredentialsAsync()
{
TokenAcquirerFactory tokenAcquirerFactory = TokenAcquirerFactory.GetDefaultInstance();
IServiceCollection services = tokenAcquirerFactory.Services;

services.Configure<MicrosoftIdentityApplicationOptions>(s_optionName, option =>
{
option.Instance = "https://login.microsoftonline.com/";
option.TenantId = "msidentitysamplestesting.onmicrosoft.com";
option.ClientId = "6af093f3-b445-4b7a-beae-046864468ad6";
option.ClientCredentials = s_clientCredentials;
});

services.AddInMemoryTokenCaches();
var serviceProvider = tokenAcquirerFactory.Build();
var options = serviceProvider.GetRequiredService<IOptionsMonitor<MicrosoftIdentityApplicationOptions>>().Get(s_optionName);
var credentialsLoader = serviceProvider.GetRequiredService<ICredentialsLoader>();
await credentialsLoader.LoadCredentialsIfNeededAsync(options.ClientCredentials!.First());
var cert = options.ClientCredentials!.First().Certificate;

// Get the token acquisition service
ITokenAcquirer tokenAcquirer = tokenAcquirerFactory.GetTokenAcquirer(s_optionName);
RsaSecurityKey rsaSecurityKey = CreateRsaSecurityKey();
var result = await tokenAcquirer.GetTokenForAppAsync("https://graph.microsoft.com/.default",
new TokenAcquisitionOptions()
{
PopPublicKey = rsaSecurityKey.KeyId,
JwkClaim = CreateJwkClaim(rsaSecurityKey, SecurityAlgorithms.RsaSha256)
});
Assert.NotNull(result.AccessToken);
}

private static string CreateJwkClaim(RsaSecurityKey key, string algorithm)
{
var parameters = key.Rsa == null ? key.Parameters : key.Rsa.ExportParameters(false);
return "{\"kty\":\"RSA\",\"n\":\"" + Base64UrlEncoder.Encode(parameters.Modulus) + "\",\"e\":\"" + Base64UrlEncoder.Encode(parameters.Exponent) + "\",\"alg\":\"" + algorithm + "\",\"kid\":\"" + key.KeyId + "\"}";
}

private static RsaSecurityKey CreateRsaSecurityKey()
{
#if NET472
RSA rsa = RSA.Create(2048);
#else
RSA rsa = new RSACryptoServiceProvider(2048);
#endif
// the reason for creating the RsaSecurityKey from RSAParameters is so that a SignatureProvider created with this key
// will own the RSA object and dispose it. If we pass a RSA object, the SignatureProvider does not own the object, the RSA object will not be disposed.
RSAParameters rsaParameters = rsa.ExportParameters(true);
RsaSecurityKey rsaSecuirtyKey = new RsaSecurityKey(rsaParameters) { KeyId = CreateRsaKeyId(rsaParameters) };
rsa.Dispose();
return rsaSecuirtyKey;
}

private static string CreateRsaKeyId(RSAParameters rsaParameters)
{
byte[] kidBytes = new byte[rsaParameters.Exponent.Length + rsaParameters.Modulus.Length];
Array.Copy(rsaParameters.Exponent, 0, kidBytes, 0, rsaParameters.Exponent.Length);
Array.Copy(rsaParameters.Modulus, 0, kidBytes, rsaParameters.Exponent.Length, rsaParameters.Modulus.Length);
using (var sha2 = SHA256.Create())
return Base64UrlEncoder.Encode(sha2.ComputeHash(kidBytes));
}

private string? ComputePublicKeyString(X509Certificate2? certificate)
{
if (certificate == null)
Expand All @@ -159,8 +225,6 @@ public async Task AcquireTokenWithPop_ClientCredentialsAsync()
return keyId;
}



private static async Task CreateGraphClientAndAssert(TokenAcquirerFactory tokenAcquirerFactory, IServiceCollection services)
{
services.AddInMemoryTokenCaches();
Expand Down