Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Westinm/trimming #2210

Merged
merged 16 commits into from
May 13, 2023
Merged
Show file tree
Hide file tree
Changes from 12 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
12 changes: 8 additions & 4 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
</PropertyGroup>

<PropertyGroup Condition="'$(TargetFramework)' == 'net6.0' or '$(TargetFramework)' == 'net7.0'">
westin-m marked this conversation as resolved.
Show resolved Hide resolved
<IsTrimmable>true</IsTrimmable>
</PropertyGroup>
Copy link
Collaborator

Choose a reason for hiding this comment

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

Do we also want to try

<EnableMicrosoftExtensionsConfigurationBinderSourceGenerator>true</EnableMicrosoftExtensionsConfigurationBinderSourceGenerator>

if we use Microsoft.Extensions.Configuration.Binder NuGet package 8.*?

and then remove the attributes which are due to the binding.

Shall we do that when we enable .NET 8?
@jennyf19 @westin-m ?

Copy link
Collaborator

Choose a reason for hiding this comment

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

Let's do that as an increment.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes, I want to try this with .NET 8.


<PropertyGroup Condition="'$(TF_BUILD)' == 'true'">
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
</PropertyGroup>
Expand Down Expand Up @@ -105,17 +109,17 @@
<MicrosoftAspNetCoreAuthenticationJwtBearerVersion>5.0.12-*</MicrosoftAspNetCoreAuthenticationJwtBearerVersion>
<MicrosoftAspNetCoreAuthenticationOpenIdConnectVersion>5.0.12-*</MicrosoftAspNetCoreAuthenticationOpenIdConnectVersion>
<MicrosoftExtensionsCachingMemoryVersion>5.0.0</MicrosoftExtensionsCachingMemoryVersion>
<!-- Microsoft.Extensions.Hosting 5.* are obsoleted -->
<!-- Microsoft.Extensions.Hosting 5.* are obsoleted -->
<MicrosoftExtensionsHostingVersion>6.0.0</MicrosoftExtensionsHostingVersion>
<MicrosoftAspNetCoreDataProtectionVersion>5.0.8</MicrosoftAspNetCoreDataProtectionVersion>
<SystemSecurityCryptographyXmlVersion>6.0.1</SystemSecurityCryptographyXmlVersion>

<!-- CVE-2022-34716 due to DataProtection 5.0.8 -->
<MicrosoftExtensionsLoggingVersion>5.0.0</MicrosoftExtensionsLoggingVersion>
<SystemTextEncodingsWebVersion>6.0.0</SystemTextEncodingsWebVersion>

<!-- Microsoft.Extensions.Configuration.Binder 6.* are obsoleted -->
<MicrosoftExtensionsConfigurationBinderVersion>6.0.0</MicrosoftExtensionsConfigurationBinderVersion>
<MicrosoftExtensionsConfigurationBinderVersion>6.0.0</MicrosoftExtensionsConfigurationBinderVersion>
<MicrosoftExtensionsDependencyInjectionVersion>2.1.0</MicrosoftExtensionsDependencyInjectionVersion>
</PropertyGroup>

Expand Down
21 changes: 20 additions & 1 deletion src/Microsoft.Identity.Web.DownstreamApi/DownstreamApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.Security.Claims;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -217,6 +218,15 @@ public Task<HttpResponseMessage> CallApiForAppAsync(
return clonedOptions;
}

#if NET6_0_OR_GREATER
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(HttpContent))]
[JsonSerializable(typeof(string))]
internal partial class SourceGenerationContext : JsonSerializerContext
{
}
#endif

private static HttpContent? SerializeInput<TInput>(TInput input, DownstreamApiOptions effectiveOptions)
{
HttpContent? effectiveInput;
Expand All @@ -231,13 +241,18 @@ public Task<HttpResponseMessage> CallApiForAppAsync(
else
{
#pragma warning disable CA2000 // Dispose objects before losing scope
#if NET6_0_OR_GREATER
effectiveInput = new StringContent(JsonSerializer.Serialize(input, typeof(TInput), SourceGenerationContext.Default), Encoding.UTF8, "application/json");
#else
effectiveInput = new StringContent(JsonSerializer.Serialize(input), Encoding.UTF8, "application/json");
#endif
#pragma warning restore CA2000 // Dispose objects before losing scope
}

return effectiveInput;
}


private static async Task<TOutput?> DeserializeOutput<TOutput>(HttpResponseMessage response, DownstreamApiOptions effectiveOptions)
where TOutput : class
{
Expand Down Expand Up @@ -270,8 +285,12 @@ public Task<HttpResponseMessage> CallApiForAppAsync(
else
{
string stringContent = await content.ReadAsStringAsync();
#if NET6_0_OR_GREATER
return (TOutput?)JsonSerializer.Deserialize(stringContent, typeof(TOutput), SourceGenerationContext.Default);
#else
return JsonSerializer.Deserialize<TOutput>(stringContent, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
}
#endif
}
}

private async Task<HttpResponseMessage> CallApiInternalAsync(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT License.

using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Identity.Abstractions;
Expand All @@ -21,6 +22,9 @@ public static class DownstreamApiExtensions
/// This is the name used when calling the service from controller/pages.</param>
/// <param name="configuration">Configuration.</param>
/// <returns>The builder for chaining.</returns>
#if NET6_0_OR_GREATER
[RequiresUnreferencedCode("Microsoft.Extensions.DependencyInjection.OptionsConfigurationServiceCollectionExtensions.Configure<TOptions>(IServiceCollection, String, IConfiguration).")]
#endif
public static IServiceCollection AddDownstreamApi(
this IServiceCollection services,
string serviceName,
Expand Down Expand Up @@ -65,6 +69,9 @@ public static IServiceCollection AddDownstreamApi(
/// This is the name used when calling the service from controller/pages.</param>
/// <param name="configuration">Configuration.</param>
/// <returns>The builder for chaining.</returns>
#if NET6_0_OR_GREATER
[RequiresUnreferencedCode("Microsoft.Identity.Web.DownstreamApiExtensions.AddDownstreamApi(IServiceCollection, String, IConfiguration).")]
#endif
public static MicrosoftIdentityAppCallsWebApiAuthenticationBuilder AddDownstreamApi(
this MicrosoftIdentityAppCallsWebApiAuthenticationBuilder builder,
string serviceName,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
Expand All @@ -24,6 +25,9 @@ public static class MicrosoftGraphExtensions
/// <param name="builder">Builder.</param>
/// <param name="configurationSection">Configuration section.</param>
/// <returns>The builder to chain.</returns>
#if NET6_0_OR_GREATER
[RequiresUnreferencedCode("Microsoft.Extensions.Configuration.ConfigurationBinder.Bind(IConfiguration, Object).")]
#endif
public static MicrosoftIdentityAppCallsWebApiAuthenticationBuilder AddMicrosoftGraph(
this MicrosoftIdentityAppCallsWebApiAuthenticationBuilder builder,
IConfigurationSection configurationSection)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNetCore.Builder;

namespace Microsoft.Identity.Web
Expand All @@ -9,6 +10,9 @@ namespace Microsoft.Identity.Web
/// Extension class on IApplicationBuilder to initialize the service provider of
/// the TokenAcquirerFactory in ASP.NET Core.
/// </summary>
#if NET6_0_OR_GREATER
[RequiresUnreferencedCode("Microsoft.Identity.Web.TokenAcquirerFactory.GetDefaultInstance(String).")]
#endif
public static class ApplicationBuilderExtensions
{
/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Net.Http;
Expand Down Expand Up @@ -138,6 +139,9 @@ public void ReplyForbiddenWithWwwAuthenticateHeader(
/// }
/// </code>
/// </example>
#if NET6_0_OR_GREATER
[RequiresUnreferencedCode("Calls Microsoft.Identity.Web.TokenAcquisition.AddAccountToCacheFromAuthorizationCodeAsync(AuthCodeRedemptionParameters)")]
#endif
public async Task AddAccountToCacheFromAuthorizationCodeAsync(
AuthorizationCodeReceivedContext context,
IEnumerable<string> scopes,
Expand Down
7 changes: 7 additions & 0 deletions src/Microsoft.Identity.Web.TokenAcquisition/ClientInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT License.

using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Identity.Web.Util;
Expand All @@ -16,6 +17,9 @@ internal class ClientInfo
[JsonPropertyName(ClaimConstants.UniqueTenantIdentifier)]
public string? UniqueTenantIdentifier { get; set; } = null;

#if NET6_0_OR_GREATER
[RequiresUnreferencedCode("Calls Microsoft.Identity.Web.ClientInfo.DeserializeFromJson(byte[]).")]
#endif
public static ClientInfo? CreateFromJson(string? clientInfo)
{
if (string.IsNullOrEmpty(clientInfo))
Expand All @@ -27,6 +31,9 @@ internal class ClientInfo
return bytes != null ? DeserializeFromJson(bytes) : null;
}

#if NET6_0_OR_GREATER
[RequiresUnreferencedCode("Calls System.Text.Json.JsonSerializer.Deserialize<TValue>(ReadOnlySpan<Byte>, JsonSerializerOptions).")]
#endif
internal static ClientInfo? DeserializeFromJson(byte[]? jsonByteArray)
{
if (jsonByteArray == null || jsonByteArray.Length == 0)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT License.

using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Security.Claims;
using System.Threading.Tasks;
#if !NETSTANDARD2_0 && !NET462 && !NET472
Expand Down Expand Up @@ -48,6 +49,9 @@ internal interface ITokenAcquisitionInternal : ITokenAcquisition
/// }
/// </code>
/// </example>
#if NET6_0_OR_GREATER
[RequiresUnreferencedCode("Calls Microsoft.Identity.Web.TokenAcquisition.AddAccountToCacheFromAuthorizationCodeAsync(AuthCodeRedemptionParameters)")]
#endif
Task AddAccountToCacheFromAuthorizationCodeAsync(
AuthorizationCodeReceivedContext context,
IEnumerable<string> scopes,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT License.

using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
Expand All @@ -18,6 +19,9 @@ namespace Microsoft.Identity.Web
/// </summary>
public class MicrosoftIdentityAppCallsWebApiAuthenticationBuilder : MicrosoftIdentityBaseAuthenticationBuilder
{
#if NET6_0_OR_GREATER
[RequiresUnreferencedCode("Calls Microsoft.Identity.Web.MicrosoftIdentityBaseAuthenticationBuilder.MicrosoftIdentityBaseAuthenticationBuilder(IServiceCollection, IConfigurationSection)")]
#endif
internal MicrosoftIdentityAppCallsWebApiAuthenticationBuilder(
IServiceCollection services,
IConfigurationSection? configurationSection = null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using Microsoft.IdentityModel.Abstractions;
using Microsoft.IdentityModel.LoggingExtensions;
using Microsoft.IdentityModel.Logging;
using System.Diagnostics.CodeAnalysis;

namespace Microsoft.Identity.Web
{
Expand All @@ -22,6 +23,9 @@ public class MicrosoftIdentityBaseAuthenticationBuilder
/// </summary>
/// <param name="services">The services being configured.</param>
/// <param name="configurationSection">Optional configuration section.</param>
#if NET6_0_OR_GREATER
[RequiresUnreferencedCode("Calls Microsoft.Extensions.Configuration.ConfigurationBinder.Bind(IConfiguration, Object).")]
Copy link
Collaborator

Choose a reason for hiding this comment

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

Can we do better in .NET 8? by enabling EnableMicrosoftExtensionsConfigurationBinderSourceGenerator ?
https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-8#source-generator-for-configuration-binding

Copy link
Contributor Author

Choose a reason for hiding this comment

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

From what I read, probably. I do want to try this and test it when we add .NET 8.

#endif
protected MicrosoftIdentityBaseAuthenticationBuilder(
IServiceCollection services,
IConfigurationSection? configurationSection = null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
Expand Down Expand Up @@ -73,6 +74,9 @@ protected TokenAcquirerFactory()
/// [!code-csharp[ConvertType](~/../tests/DevApps/aspnet-mvc/OwinWebApp/App_Start/Startup.Auth.cs?highlight=22)]
/// ]]></format>
/// </example>
#if NET6_0_OR_GREATER
[RequiresUnreferencedCode("Calls Microsoft.Extensions.Configuration.ConfigurationBinder.Bind(IConfiguration, Object).")]
#endif
static public T GetDefaultInstance<T>(string configSection="AzureAd") where T : TokenAcquirerFactory, new()
{
T instance;
Expand Down Expand Up @@ -108,6 +112,9 @@ protected TokenAcquirerFactory()
/// [!code-csharp[ConvertType](~/../tests/DevApps/daemon-app/daemon-console-calling-msgraph/Program.cs?highlight=5)]
/// ]]></format>
/// </example>
#if NET6_0_OR_GREATER
[RequiresUnreferencedCode("Calls Microsoft.Extensions.Configuration.ConfigurationBinder.Bind(IConfiguration, Object).")]
#endif
static public TokenAcquirerFactory GetDefaultInstance(string configSection = "AzureAd")
{
TokenAcquirerFactory instance;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
Expand Down Expand Up @@ -102,6 +103,9 @@ public TokenAcquisition(
_credentialsLoader = credentialsLoader;
}

#if NET6_0_OR_GREATER
[RequiresUnreferencedCode("Calls Microsoft.Identity.Web.ClientInfo.CreateFromJson(String)")]
#endif
public async Task<AcquireTokenResult> AddAccountToCacheFromAuthorizationCodeAsync(
AuthCodeRedemptionParameters authCodeRedemptionParameters)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT License.

using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Identity.Abstractions;
Expand All @@ -25,6 +26,9 @@ public static class WebApiBuilders
/// <param name="services">The services being configured.</param>
/// <param name="configuration">IConfigurationSection.</param>
/// <returns>The authentication builder to chain.</returns>
#if NET6_0_OR_GREATER
[RequiresUnreferencedCode("Calls Bind, Configure with Unspecified Configuration and ServiceCollection.")]
#endif
public static MicrosoftIdentityAppCallsWebApiAuthenticationBuilder EnableTokenAcquisition(
Action<ConfidentialClientApplicationOptions> configureConfidentialClientApplicationOptions,
string authenticationScheme,
Expand Down
3 changes: 2 additions & 1 deletion src/Microsoft.Identity.Web/AuthorizeForScopesAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT License.

using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
Expand Down Expand Up @@ -89,7 +90,7 @@ public override void OnException(ExceptionContext context)
IDWebErrorMessage.ScopeKeySectionIsProvidedButNotPresentInTheServicesCollection,
nameof(ScopeKeySection)));
}
string? scopeKeySectionValue = configuration.GetValue<string>(ScopeKeySection);
string? scopeKeySectionValue = configuration[ScopeKeySection];
Copy link
Collaborator

Choose a reason for hiding this comment

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

Can the section be a single property value? Did you test it?


if (!string.IsNullOrEmpty(scopeKeySectionValue))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
Expand Down Expand Up @@ -107,6 +108,9 @@ public async Task<HttpResponseMessage> CallWebApiForUserAsync(
}

/// <inheritdoc/>
#if NET6_0_OR_GREATER
[RequiresUnreferencedCode("Calls System.Text.Json.JsonSerializer.Serialize<TValue>(TValue, JsonSerializerOptions).")]
#endif
public async Task<TOutput?> CallWebApiForUserAsync<TInput, TOutput>(
string serviceName,
TInput input,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

Expand All @@ -24,6 +25,9 @@ public static class DownstreamWebApiExtensions
[Obsolete("Use AddDownstreamApi in Microsoft.Identity.Abstractions, implemented in Microsoft.Identity.Web.DownstreamApi." +
"See aka.ms/id-web-downstream-api-v2 for migration details.", false)]
[EditorBrowsable(EditorBrowsableState.Never)]
#if NET6_0_OR_GREATER
[RequiresUnreferencedCode("Calls Microsoft.Extensions.DependencyInjection.OptionsConfigurationServiceCollectionExtensions.Configure<TOutput>(IServiceCollection, String, IConfiguration).")]
#endif
public static MicrosoftIdentityAppCallsWebApiAuthenticationBuilder AddDownstreamWebApi(
this MicrosoftIdentityAppCallsWebApiAuthenticationBuilder builder,
string serviceName,
Expand Down
Loading