diff --git a/Microsoft.Identity.Web.sln b/Microsoft.Identity.Web.sln index 37c8b793b..20cbe7559 100644 --- a/Microsoft.Identity.Web.sln +++ b/Microsoft.Identity.Web.sln @@ -156,6 +156,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TokenAcquirerTests", "Token EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Identity.Web.DownstreamRestApi", "src\Microsoft.Identity.Web.DownstreamRestApi\Microsoft.Identity.Web.DownstreamRestApi.csproj", "{A123BD94-812D-40EC-9576-1A7AB5C59913}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Identity.Web.Diagnostics", "src\Microsoft.Identity.Web.Diagnostics\Microsoft.Identity.Web.Diagnostics.csproj", "{982F70B7-4D85-42B7-ABDD-7EDD2081360A}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -330,6 +332,10 @@ Global {A123BD94-812D-40EC-9576-1A7AB5C59913}.Debug|Any CPU.Build.0 = Debug|Any CPU {A123BD94-812D-40EC-9576-1A7AB5C59913}.Release|Any CPU.ActiveCfg = Release|Any CPU {A123BD94-812D-40EC-9576-1A7AB5C59913}.Release|Any CPU.Build.0 = Release|Any CPU + {982F70B7-4D85-42B7-ABDD-7EDD2081360A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {982F70B7-4D85-42B7-ABDD-7EDD2081360A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {982F70B7-4D85-42B7-ABDD-7EDD2081360A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {982F70B7-4D85-42B7-ABDD-7EDD2081360A}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 317b4b9b1..2b114a774 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -55,7 +55,7 @@ - 9.0 + 10.0 diff --git a/src/Microsoft.Identity.Web.Certificate/CertificateDescription.cs b/src/Microsoft.Identity.Web.Certificate/CertificateDescription.cs index 094e01852..022e75fdc 100644 --- a/src/Microsoft.Identity.Web.Certificate/CertificateDescription.cs +++ b/src/Microsoft.Identity.Web.Certificate/CertificateDescription.cs @@ -25,10 +25,8 @@ public CertificateDescription() /// public CertificateDescription(CredentialDescription credentialDescription) { - if (credentialDescription is null) - { - throw new ArgumentNullException(nameof(credentialDescription)); - } + _ = Throws.IfNull(credentialDescription); + // TODO: Check credentialDescription is really a cert SourceType = (CertificateSource)credentialDescription.SourceType; Container = credentialDescription.Container; diff --git a/src/Microsoft.Identity.Web.Certificate/DefaultCertificateLoader.cs b/src/Microsoft.Identity.Web.Certificate/DefaultCertificateLoader.cs index 02b0ab1aa..70e5dfe75 100644 --- a/src/Microsoft.Identity.Web.Certificate/DefaultCertificateLoader.cs +++ b/src/Microsoft.Identity.Web.Certificate/DefaultCertificateLoader.cs @@ -60,10 +60,7 @@ public static string? UserAssignedManagedIdentityClientId /// Description of the credential. public void LoadCredentialsIfNeeded(CredentialDescription credentialDescription) { - if (credentialDescription == null) - { - throw new ArgumentNullException(nameof(credentialDescription)); - } + _ = Throws.IfNull(credentialDescription); if (credentialDescription.CachedValue == null) { diff --git a/src/Microsoft.Identity.Web.Certificate/Microsoft.Identity.Web.Certificate.csproj b/src/Microsoft.Identity.Web.Certificate/Microsoft.Identity.Web.Certificate.csproj index 0d712fba5..14e7511c0 100644 --- a/src/Microsoft.Identity.Web.Certificate/Microsoft.Identity.Web.Certificate.csproj +++ b/src/Microsoft.Identity.Web.Certificate/Microsoft.Identity.Web.Certificate.csproj @@ -11,6 +11,10 @@ - + + + + + diff --git a/src/Microsoft.Identity.Web.Diagnostics/Diagnostics/CallerArgumentExpressionAttribute.cs b/src/Microsoft.Identity.Web.Diagnostics/Diagnostics/CallerArgumentExpressionAttribute.cs new file mode 100644 index 000000000..eef189e05 --- /dev/null +++ b/src/Microsoft.Identity.Web.Diagnostics/Diagnostics/CallerArgumentExpressionAttribute.cs @@ -0,0 +1,18 @@ +#if !NETCOREAPP3_1_OR_GREATER +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace System.Runtime.CompilerServices +{ + [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] + internal sealed class CallerArgumentExpressionAttribute : Attribute + { + public CallerArgumentExpressionAttribute(string parameterName) + { + ParameterName = parameterName; + } + + public string ParameterName { get; } + } +} +#endif diff --git a/src/Microsoft.Identity.Web.Diagnostics/Diagnostics/NullableAttributes.cs b/src/Microsoft.Identity.Web.Diagnostics/Diagnostics/NullableAttributes.cs new file mode 100644 index 000000000..9a9e6b730 --- /dev/null +++ b/src/Microsoft.Identity.Web.Diagnostics/Diagnostics/NullableAttributes.cs @@ -0,0 +1,202 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +#if !NETCOREAPP3_1_OR_GREATER +namespace System.Diagnostics.CodeAnalysis +{ +#if !NETSTANDARD2_1 + /// Specifies that null is allowed as an input even if the corresponding type disallows it. + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)] +#if SYSTEM_PRIVATE_CORELIB + public +#else + internal +#endif + sealed class AllowNullAttribute : Attribute + { } + + /// Specifies that null is disallowed as an input even if the corresponding type allows it. + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)] +#if SYSTEM_PRIVATE_CORELIB + public +#else + internal +#endif + sealed class DisallowNullAttribute : Attribute + { } + + /// Specifies that an output may be null even if the corresponding type disallows it. + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)] +#if SYSTEM_PRIVATE_CORELIB + public +#else + internal +#endif + sealed class MaybeNullAttribute : Attribute + { } + + /// Specifies that an output will not be null even if the corresponding type allows it. Specifies that an input argument was not null when the call returns. + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)] +#if SYSTEM_PRIVATE_CORELIB + public +#else + internal +#endif + sealed class NotNullAttribute : Attribute + { } + + /// Specifies that when a method returns , the parameter may be null even if the corresponding type disallows it. + [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +#if SYSTEM_PRIVATE_CORELIB + public +#else + internal +#endif + sealed class MaybeNullWhenAttribute : Attribute + { + /// Initializes the attribute with the specified return value condition. + /// + /// The return value condition. If the method returns this value, the associated parameter may be null. + /// + public MaybeNullWhenAttribute(bool returnValue) => ReturnValue = returnValue; + + /// Gets the return value condition. + public bool ReturnValue { get; } + } + + /// Specifies that when a method returns , the parameter will not be null even if the corresponding type allows it. + [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +#if SYSTEM_PRIVATE_CORELIB + public +#else + internal +#endif + sealed class NotNullWhenAttribute : Attribute + { + /// Initializes the attribute with the specified return value condition. + /// + /// The return value condition. If the method returns this value, the associated parameter will not be null. + /// + public NotNullWhenAttribute(bool returnValue) => ReturnValue = returnValue; + + /// Gets the return value condition. + public bool ReturnValue { get; } + } + + /// Specifies that the output will be non-null if the named parameter is non-null. + [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] +#if SYSTEM_PRIVATE_CORELIB + public +#else + internal +#endif + sealed class NotNullIfNotNullAttribute : Attribute + { + /// Initializes the attribute with the associated parameter name. + /// + /// The associated parameter name. The output will be non-null if the argument to the parameter specified is non-null. + /// + public NotNullIfNotNullAttribute(string parameterName) => ParameterName = parameterName; + + /// Gets the associated parameter name. + public string ParameterName { get; } + } + + /// Applied to a method that will never return under any circumstance. + [AttributeUsage(AttributeTargets.Method, Inherited = false)] +#if SYSTEM_PRIVATE_CORELIB + public +#else + internal +#endif + sealed class DoesNotReturnAttribute : Attribute + { } + + /// Specifies that the method will not return if the associated Boolean parameter is passed the specified value. + [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +#if SYSTEM_PRIVATE_CORELIB + public +#else + internal +#endif + sealed class DoesNotReturnIfAttribute : Attribute + { + /// Initializes the attribute with the specified parameter value. + /// + /// The condition parameter value. Code after the method will be considered unreachable by diagnostics if the argument to + /// the associated parameter matches this value. + /// + public DoesNotReturnIfAttribute(bool parameterValue) => ParameterValue = parameterValue; + + /// Gets the condition parameter value. + public bool ParameterValue { get; } + } +#endif + + /// Specifies that the method or property will ensure that the listed field and property members have not-null values. + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] +#if SYSTEM_PRIVATE_CORELIB + public +#else + internal +#endif + sealed class MemberNotNullAttribute : Attribute + { + /// Initializes the attribute with a field or property member. + /// + /// The field or property member that is promised to be not-null. + /// + public MemberNotNullAttribute(string member) => Members = new[] { member }; + + /// Initializes the attribute with the list of field and property members. + /// + /// The list of field and property members that are promised to be not-null. + /// + public MemberNotNullAttribute(params string[] members) => Members = members; + + /// Gets field or property member names. + public string[] Members { get; } + } + + /// Specifies that the method or property will ensure that the listed field and property members have not-null values when returning with the specified return value condition. + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] +#if SYSTEM_PRIVATE_CORELIB + public +#else + internal +#endif + sealed class MemberNotNullWhenAttribute : Attribute + { + /// Initializes the attribute with the specified return value condition and a field or property member. + /// + /// The return value condition. If the method returns this value, the associated parameter will not be null. + /// + /// + /// The field or property member that is promised to be not-null. + /// + public MemberNotNullWhenAttribute(bool returnValue, string member) + { + ReturnValue = returnValue; + Members = new[] { member }; + } + + /// Initializes the attribute with the specified return value condition and list of field and property members. + /// + /// The return value condition. If the method returns this value, the associated parameter will not be null. + /// + /// + /// The list of field and property members that are promised to be not-null. + /// + public MemberNotNullWhenAttribute(bool returnValue, params string[] members) + { + ReturnValue = returnValue; + Members = members; + } + + /// Gets the return value condition. + public bool ReturnValue { get; } + + /// Gets field or property member names. + public string[] Members { get; } + } +} +#endif diff --git a/src/Microsoft.Identity.Web.Diagnostics/Diagnostics/Throws.cs b/src/Microsoft.Identity.Web.Diagnostics/Diagnostics/Throws.cs new file mode 100644 index 000000000..1659b3532 --- /dev/null +++ b/src/Microsoft.Identity.Web.Diagnostics/Diagnostics/Throws.cs @@ -0,0 +1,379 @@ +// © Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; + +namespace Microsoft.Identity.Web +{ + /// + /// Defines static methods used to throw exceptions. + /// + /// + /// The main purpose is to reduce code size, improve performance, and standardize exception + /// messages. + /// + [SuppressMessage("Minor Code Smell", "S4136:Method overloads should be grouped together", Justification = "Doesn't work with the region layout")] + internal static partial class Throws + { + #region For Object + + /// + /// Throws an if the specified argument is . + /// + /// Argument type to be checked for . + /// Object to be checked for . + /// The name of the parameter being checked. + /// The original value of . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [return: NotNull] + public static T IfNull([NotNull] T argument, [CallerArgumentExpression("argument")] string paramName = "") + { + if (argument is null) + { + ArgumentNullException(paramName); + } + + return argument; + } + + /// + /// Throws an if the specified argument is , + /// or if the specified member is . + /// + /// Argument type to be checked for . + /// Member type to be checked for . + /// Argument to be checked for . + /// Object member to be checked for . + /// The name of the parameter being checked. + /// The name of the member. + /// The original value of . + /// + /// + /// Throws.IfNullOrMemberNull(myObject, myObject?.MyProperty) + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [return: NotNull] + public static TMember IfNullOrMemberNull( + [NotNull] TParameter argument, + [NotNull] TMember member, + [CallerArgumentExpression("argument")] string paramName = "", + [CallerArgumentExpression("member")] string memberName = "") + { + if (argument is null) + { + ArgumentNullException(paramName); + } + + if (member is null) + { + ArgumentException(paramName, $"Member {memberName} of {paramName} is null"); + } + + return member; + } + + /// + /// Throws an if the specified member is . + /// + /// Argument type. + /// Member type to be checked for . + /// Argument to which member belongs. + /// Object member to be checked for . + /// The name of the parameter being checked. + /// The name of the member. + /// The original value of . + /// + /// + /// Throws.IfMemberNull(myObject, myObject.MyProperty) + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [return: NotNull] + [SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Analyzer isn't seeing the reference to 'argument' in the attribute")] + public static TMember IfMemberNull( + TParameter argument, + [NotNull] TMember member, + [CallerArgumentExpression("argument")] string paramName = "", + [CallerArgumentExpression("member")] string memberName = "") + where TParameter : notnull + { + if (member is null) + { + ArgumentException(paramName, $"Member {memberName} of {paramName} is null"); + } + + return member; + } + + #endregion + + #region For String + + /// + /// Throws either an or an + /// if the specified string is or whitespace respectively. + /// + /// String to be checked for or whitespace. + /// The name of the parameter being checked. + /// The original value of . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [return: NotNull] + public static string IfNullOrWhitespace([NotNull] string? argument, [CallerArgumentExpression("argument")] string paramName = "") + { +#if !NETCOREAPP3_1_OR_GREATER + if (argument == null) + { + ArgumentNullException(paramName); + } +#endif + + if (string.IsNullOrWhiteSpace(argument)) + { + if (argument == null) + { + ArgumentNullException(paramName); + } + else + { + ArgumentException(paramName, "Argument is whitespace"); + } + } + + return argument; + } + + /// + /// Throws an if the string is , + /// or if it is empty. + /// + /// String to be checked for or empty. + /// The name of the parameter being checked. + /// The original value of . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [return: NotNull] + public static string IfNullOrEmpty([NotNull] string? argument, [CallerArgumentExpression("argument")] string paramName = "") + { +#if !NETCOREAPP3_1_OR_GREATER + if (argument == null) + { + ArgumentNullException(paramName); + } +#endif + + if (string.IsNullOrEmpty(argument)) + { + if (argument == null) + { + ArgumentNullException(paramName); + } + else + { + ArgumentException(paramName, "Argument is an empty string"); + } + } + + return argument; + } + + #endregion + + #region For Buffer + + /// + /// Throws an if the argument's buffer size is less than the required buffer size. + /// + /// The actual buffer size. + /// The required buffer size. + /// The name of the parameter to be checked. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void IfBufferTooSmall(int bufferSize, int requiredSize, string paramName = "") + { + if (bufferSize < requiredSize) + { + ArgumentException(paramName, $"Buffer too small, needed a size of {requiredSize} but got {bufferSize}"); + } + } + + #endregion + + #region For Enums + + /// + /// Throws an if the enum value is not valid. + /// + /// The argument to evaluate. + /// The name of the parameter being checked. + /// The type of the enumeration. + /// The original value of . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T IfOutOfRange(T argument, [CallerArgumentExpression("argument")] string paramName = "") + where T : struct, Enum + { +#if NET5_0_OR_GREATER + if (!Enum.IsDefined(argument)) +#else + if (!Enum.IsDefined(typeof(T), argument)) +#endif + { + ArgumentOutOfRangeException(paramName, $"{argument} is an invalid value for enum type {typeof(T)}"); + } + + return argument; + } + + #endregion + + #region For Collections + + /// + /// Throws an if the collection is , + /// or if it is empty. + /// + /// The collection to evaluate. + /// The name of the parameter being checked. + /// The type of objects in the collection. + /// The original value of . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [return: NotNull] + public static ICollection IfNullOrEmpty([NotNull] ICollection? argument, [CallerArgumentExpression("argument")] string paramName = "") + { + if (argument == null) + { + ArgumentNullException(paramName); + } + else if (argument.Count == 0) + { + ArgumentException(paramName, "Collection is empty"); + } + + return argument; + } + + /// + /// Throws an if the collection is , + /// or if it is empty. + /// + /// The collection to evaluate. + /// The name of the parameter being checked. + /// The type of objects in the collection. + /// The original value of . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [return: NotNull] + public static IReadOnlyCollection IfNullOrEmpty([NotNull] IReadOnlyCollection? argument, [CallerArgumentExpression("argument")] string paramName = "") + { + if (argument == null) + { + ArgumentNullException(paramName); + } + else if (argument.Count == 0) + { + ArgumentException(paramName, "Collection is empty"); + } + + return argument; + } + + #endregion + + #region Exceptions + + /// + /// Throws an . + /// + /// The name of the parameter that caused the exception. + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + public static void ArgumentNullException(string paramName) + => throw new ArgumentNullException(paramName); + + /// + /// Throws an . + /// + /// The name of the parameter that caused the exception. + /// A message that describes the error. + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + public static void ArgumentNullException(string paramName, string? message) + => throw new ArgumentNullException(paramName, message); + + /// + /// Throws an . + /// + /// The name of the parameter that caused the exception. + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + public static void ArgumentOutOfRangeException(string paramName) + => throw new ArgumentOutOfRangeException(paramName); + + /// + /// Throws an . + /// + /// The name of the parameter that caused the exception. + /// A message that describes the error. + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + public static void ArgumentOutOfRangeException(string paramName, string? message) + => throw new ArgumentOutOfRangeException(paramName, message); + + /// + /// Throws an . + /// + /// The name of the parameter that caused the exception. + /// The value of the argument that caused this exception. + /// A message that describes the error. + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + public static void ArgumentOutOfRangeException(string paramName, object? actualValue, string? message) + => throw new ArgumentOutOfRangeException(paramName, actualValue, message); + + /// + /// Throws an . + /// + /// The name of the parameter that caused the exception. + /// A message that describes the error. + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + public static void ArgumentException(string paramName, string? message) + => throw new ArgumentException(message, paramName); + + /// + /// Throws an . + /// + /// The name of the parameter that caused the exception. + /// A message that describes the error. + /// The exception that is the cause of the current exception. + /// + /// If the is not a , the current exception is raised in a catch + /// block that handles the inner exception. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + public static void ArgumentException(string paramName, string? message, Exception? innerException) + => throw new ArgumentException(message, paramName, innerException); + + /// + /// Throws an . + /// + /// A message that describes the error. + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + public static void InvalidOperationException(string message) + => throw new InvalidOperationException(message); + + /// + /// Throws an . + /// + /// A message that describes the error. + /// The exception that is the cause of the current exception. + [MethodImpl(MethodImplOptions.NoInlining)] + [DoesNotReturn] + public static void InvalidOperationException(string message, Exception? innerException) + => throw new InvalidOperationException(message, innerException); + + #endregion + } +} diff --git a/src/Microsoft.Identity.Web.Diagnostics/Microsoft.Identity.Web.Diagnostics.csproj b/src/Microsoft.Identity.Web.Diagnostics/Microsoft.Identity.Web.Diagnostics.csproj new file mode 100644 index 000000000..9a8eb67e5 --- /dev/null +++ b/src/Microsoft.Identity.Web.Diagnostics/Microsoft.Identity.Web.Diagnostics.csproj @@ -0,0 +1,13 @@ + + + + disable + enable + + + + + + diff --git a/src/Microsoft.Identity.Web.Diagnostics/Properties/InternalsVisibleTo.cs b/src/Microsoft.Identity.Web.Diagnostics/Properties/InternalsVisibleTo.cs new file mode 100644 index 000000000..673294ba7 --- /dev/null +++ b/src/Microsoft.Identity.Web.Diagnostics/Properties/InternalsVisibleTo.cs @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Runtime.CompilerServices; + +// Allow this assembly to be serviced when run on desktop CLR +[assembly: InternalsVisibleTo("Microsoft.Identity.Web, PublicKey=00240000048000009400000006020000002400005253413100040000010001002D96616729B54F6D013D71559A017F50AA4861487226C523959D1579B93F3FDF71C08B980FD3130062B03D3DE115C4B84E7AC46AEF5E192A40E7457D5F3A08F66CEAB71143807F2C3CB0DA5E23B38F0559769978406F6E5D30CEADD7985FC73A5A609A8B74A1DF0A29399074A003A226C943D480FEC96DBEC7106A87896539AD")] +[assembly: InternalsVisibleTo("Microsoft.Identity.Web.Certificate, PublicKey=00240000048000009400000006020000002400005253413100040000010001002D96616729B54F6D013D71559A017F50AA4861487226C523959D1579B93F3FDF71C08B980FD3130062B03D3DE115C4B84E7AC46AEF5E192A40E7457D5F3A08F66CEAB71143807F2C3CB0DA5E23B38F0559769978406F6E5D30CEADD7985FC73A5A609A8B74A1DF0A29399074A003A226C943D480FEC96DBEC7106A87896539AD")] +[assembly: InternalsVisibleTo("Microsoft.Identity.Web.CertificateLess, PublicKey=00240000048000009400000006020000002400005253413100040000010001002D96616729B54F6D013D71559A017F50AA4861487226C523959D1579B93F3FDF71C08B980FD3130062B03D3DE115C4B84E7AC46AEF5E192A40E7457D5F3A08F66CEAB71143807F2C3CB0DA5E23B38F0559769978406F6E5D30CEADD7985FC73A5A609A8B74A1DF0A29399074A003A226C943D480FEC96DBEC7106A87896539AD")] +[assembly: InternalsVisibleTo("Microsoft.Identity.Web.DownstreamRestApi, PublicKey=00240000048000009400000006020000002400005253413100040000010001002D96616729B54F6D013D71559A017F50AA4861487226C523959D1579B93F3FDF71C08B980FD3130062B03D3DE115C4B84E7AC46AEF5E192A40E7457D5F3A08F66CEAB71143807F2C3CB0DA5E23B38F0559769978406F6E5D30CEADD7985FC73A5A609A8B74A1DF0A29399074A003A226C943D480FEC96DBEC7106A87896539AD")] +[assembly: InternalsVisibleTo("Microsoft.Identity.Web.MicrosoftGraph, PublicKey=00240000048000009400000006020000002400005253413100040000010001002D96616729B54F6D013D71559A017F50AA4861487226C523959D1579B93F3FDF71C08B980FD3130062B03D3DE115C4B84E7AC46AEF5E192A40E7457D5F3A08F66CEAB71143807F2C3CB0DA5E23B38F0559769978406F6E5D30CEADD7985FC73A5A609A8B74A1DF0A29399074A003A226C943D480FEC96DBEC7106A87896539AD")] +[assembly: InternalsVisibleTo("Microsoft.Identity.Web.MicrosoftGraphBeta, PublicKey=00240000048000009400000006020000002400005253413100040000010001002D96616729B54F6D013D71559A017F50AA4861487226C523959D1579B93F3FDF71C08B980FD3130062B03D3DE115C4B84E7AC46AEF5E192A40E7457D5F3A08F66CEAB71143807F2C3CB0DA5E23B38F0559769978406F6E5D30CEADD7985FC73A5A609A8B74A1DF0A29399074A003A226C943D480FEC96DBEC7106A87896539AD")] +[assembly: InternalsVisibleTo("Microsoft.Identity.Web.TokenAcquisition, PublicKey=00240000048000009400000006020000002400005253413100040000010001002D96616729B54F6D013D71559A017F50AA4861487226C523959D1579B93F3FDF71C08B980FD3130062B03D3DE115C4B84E7AC46AEF5E192A40E7457D5F3A08F66CEAB71143807F2C3CB0DA5E23B38F0559769978406F6E5D30CEADD7985FC73A5A609A8B74A1DF0A29399074A003A226C943D480FEC96DBEC7106A87896539AD")] +[assembly: InternalsVisibleTo("Microsoft.Identity.Web.TokenCache, PublicKey=00240000048000009400000006020000002400005253413100040000010001002D96616729B54F6D013D71559A017F50AA4861487226C523959D1579B93F3FDF71C08B980FD3130062B03D3DE115C4B84E7AC46AEF5E192A40E7457D5F3A08F66CEAB71143807F2C3CB0DA5E23B38F0559769978406F6E5D30CEADD7985FC73A5A609A8B74A1DF0A29399074A003A226C943D480FEC96DBEC7106A87896539AD")] +[assembly: InternalsVisibleTo("Microsoft.Identity.Web.UI, PublicKey=00240000048000009400000006020000002400005253413100040000010001002D96616729B54F6D013D71559A017F50AA4861487226C523959D1579B93F3FDF71C08B980FD3130062B03D3DE115C4B84E7AC46AEF5E192A40E7457D5F3A08F66CEAB71143807F2C3CB0DA5E23B38F0559769978406F6E5D30CEADD7985FC73A5A609A8B74A1DF0A29399074A003A226C943D480FEC96DBEC7106A87896539AD")] +[assembly: InternalsVisibleTo("Microsoft.Identity.Web.OWIN, PublicKey=00240000048000009400000006020000002400005253413100040000010001002D96616729B54F6D013D71559A017F50AA4861487226C523959D1579B93F3FDF71C08B980FD3130062B03D3DE115C4B84E7AC46AEF5E192A40E7457D5F3A08F66CEAB71143807F2C3CB0DA5E23B38F0559769978406F6E5D30CEADD7985FC73A5A609A8B74A1DF0A29399074A003A226C943D480FEC96DBEC7106A87896539AD")] diff --git a/src/Microsoft.Identity.Web.DownstreamRestApi/DownstreamRestApiExtensions.cs b/src/Microsoft.Identity.Web.DownstreamRestApi/DownstreamRestApiExtensions.cs index 56eb7a440..0c78f3f5c 100644 --- a/src/Microsoft.Identity.Web.DownstreamRestApi/DownstreamRestApiExtensions.cs +++ b/src/Microsoft.Identity.Web.DownstreamRestApi/DownstreamRestApiExtensions.cs @@ -26,10 +26,7 @@ public static IServiceCollection AddDownstreamRestApi( string serviceName, IConfiguration configuration) { - if (services is null) - { - throw new ArgumentNullException(nameof(services)); - } + _ = Throws.IfNull(services); services.Configure(serviceName, configuration); services.AddScoped(); @@ -49,10 +46,7 @@ public static IServiceCollection AddDownstreamRestApi( string serviceName, Action configureOptions) { - if (services is null) - { - throw new ArgumentNullException(nameof(services)); - } + _ = Throws.IfNull(services); services.Configure(serviceName, configureOptions); diff --git a/src/Microsoft.Identity.Web.MicrosoftGraph/MicrosoftGraphExtensions.cs b/src/Microsoft.Identity.Web.MicrosoftGraph/MicrosoftGraphExtensions.cs index b62a68f97..cddfeecef 100644 --- a/src/Microsoft.Identity.Web.MicrosoftGraph/MicrosoftGraphExtensions.cs +++ b/src/Microsoft.Identity.Web.MicrosoftGraph/MicrosoftGraphExtensions.cs @@ -62,10 +62,7 @@ public static MicrosoftIdentityAppCallsWebApiAuthenticationBuilder AddMicrosoftG this MicrosoftIdentityAppCallsWebApiAuthenticationBuilder builder, Action configureMicrosoftGraphOptions) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + _ = Throws.IfNull(builder); builder.Services.AddMicrosoftGraph(configureMicrosoftGraphOptions); return builder; @@ -82,10 +79,7 @@ public static MicrosoftIdentityAppCallsWebApiAuthenticationBuilder AddMicrosoftG this MicrosoftIdentityAppCallsWebApiAuthenticationBuilder builder, Func graphServiceClientFactory, IEnumerable initialScopes) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + _ = Throws.IfNull(builder); builder.Services.AddScoped(serviceProvider => { @@ -108,10 +102,7 @@ public static MicrosoftIdentityAppCallsWebApiAuthenticationBuilder AddMicrosoftG this MicrosoftIdentityAppCallsWebApiAuthenticationBuilder builder, Func graphServiceClientFactory) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + _ = Throws.IfNull(builder); builder.Services.AddScoped(serviceProvider => { diff --git a/src/Microsoft.Identity.Web.TokenAcquisition/AspNetCore/TokenAcquisition-AspnetCore.cs b/src/Microsoft.Identity.Web.TokenAcquisition/AspNetCore/TokenAcquisition-AspnetCore.cs index 5a83dc87f..602629ad2 100644 --- a/src/Microsoft.Identity.Web.TokenAcquisition/AspNetCore/TokenAcquisition-AspnetCore.cs +++ b/src/Microsoft.Identity.Web.TokenAcquisition/AspNetCore/TokenAcquisition-AspnetCore.cs @@ -181,15 +181,8 @@ private void CheckParameters( AuthorizationCodeReceivedContext context, IEnumerable scopes) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (scopes == null) - { - throw new ArgumentNullException(nameof(scopes)); - } + _ = Throws.IfNull(context); + _ = Throws.IfNull(scopes); } } } diff --git a/src/Microsoft.Identity.Web.TokenAcquisition/Base64UrlHelpers.cs b/src/Microsoft.Identity.Web.TokenAcquisition/Base64UrlHelpers.cs index e62999a20..b839ff6f1 100644 --- a/src/Microsoft.Identity.Web.TokenAcquisition/Base64UrlHelpers.cs +++ b/src/Microsoft.Identity.Web.TokenAcquisition/Base64UrlHelpers.cs @@ -58,7 +58,7 @@ internal static class Base64UrlHelpers /// offset or length is negative OR offset plus length is greater than the length of inArray. private static string Encode(byte[] inArray, int offset, int length) { - _ = inArray ?? throw new ArgumentNullException(nameof(inArray)); + _ = Throws.IfNull(inArray); if (length == 0) { diff --git a/src/Microsoft.Identity.Web.TokenAcquisition/Microsoft.Identity.Web.TokenAcquisition.csproj b/src/Microsoft.Identity.Web.TokenAcquisition/Microsoft.Identity.Web.TokenAcquisition.csproj index 072d37318..50ef31c7b 100644 --- a/src/Microsoft.Identity.Web.TokenAcquisition/Microsoft.Identity.Web.TokenAcquisition.csproj +++ b/src/Microsoft.Identity.Web.TokenAcquisition/Microsoft.Identity.Web.TokenAcquisition.csproj @@ -24,7 +24,7 @@ - + diff --git a/src/Microsoft.Identity.Web.TokenAcquisition/ServiceCollectionExtensions.cs b/src/Microsoft.Identity.Web.TokenAcquisition/ServiceCollectionExtensions.cs index caf229da1..4bda388b6 100644 --- a/src/Microsoft.Identity.Web.TokenAcquisition/ServiceCollectionExtensions.cs +++ b/src/Microsoft.Identity.Web.TokenAcquisition/ServiceCollectionExtensions.cs @@ -39,10 +39,7 @@ public static IServiceCollection AddTokenAcquisition( this IServiceCollection services, bool isTokenAcquisitionSingleton = false) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + _ = Throws.IfNull(services); if (services.FirstOrDefault(s => s.ImplementationType == typeof(MicrosoftIdentityOptionsMerger)) == null) { diff --git a/src/Microsoft.Identity.Web.TokenAcquisition/TokenAcquirerFactory-GetTokenAcquirers.cs b/src/Microsoft.Identity.Web.TokenAcquisition/TokenAcquirerFactory-GetTokenAcquirers.cs index c55568254..8d23c5c12 100644 --- a/src/Microsoft.Identity.Web.TokenAcquisition/TokenAcquirerFactory-GetTokenAcquirers.cs +++ b/src/Microsoft.Identity.Web.TokenAcquisition/TokenAcquirerFactory-GetTokenAcquirers.cs @@ -56,10 +56,7 @@ public ITokenAcquirer GetTokenAcquirer( /// public ITokenAcquirer GetTokenAcquirer(ApplicationAuthenticationOptions applicationAuthenticationOptions) { - if (applicationAuthenticationOptions is null) - { - throw new ArgumentNullException(nameof(applicationAuthenticationOptions)); - } + _ = Throws.IfNull(applicationAuthenticationOptions); CheckServiceProviderNotNull(); diff --git a/src/Microsoft.Identity.Web.TokenAcquisition/TokenAcquisition.cs b/src/Microsoft.Identity.Web.TokenAcquisition/TokenAcquisition.cs index 69dd4a057..573c34baf 100644 --- a/src/Microsoft.Identity.Web.TokenAcquisition/TokenAcquisition.cs +++ b/src/Microsoft.Identity.Web.TokenAcquisition/TokenAcquisition.cs @@ -104,7 +104,7 @@ public async Task AddAccountToCacheFromAuthorizationCodeAsync( string? codeVerifier, string? userFlow) { - ParametersCheck(scopes); + _ = Throws.IfNull(scopes); MergedOptions mergedOptions = _tokenAcquisitionHost.GetOptions(authenticationScheme, out string effectiveAuthenticationScheme); try @@ -171,14 +171,6 @@ public async Task AddAccountToCacheFromAuthorizationCodeAsync( return authenticationScheme; } - private void ParametersCheck(IEnumerable scopes) - { - if (scopes == null) - { - throw new ArgumentNullException(nameof(scopes)); - } - } - private static string GetApplicationKey(MergedOptions mergedOptions) { return mergedOptions.Instance! + mergedOptions.ClientId; @@ -216,7 +208,7 @@ public async Task GetAuthenticationResultForUserAsync( ClaimsPrincipal? user = null, TokenAcquisitionOptions? tokenAcquisitionOptions = null) { - ParametersCheck(scopes); + _ = Throws.IfNull(scopes); MergedOptions mergedOptions = _tokenAcquisitionHost.GetOptions(authenticationScheme, out _); @@ -320,10 +312,7 @@ public Task GetAuthenticationResultForAppAsync( string? tenant = null, TokenAcquisitionOptions? tokenAcquisitionOptions = null) { - if (string.IsNullOrEmpty(scope)) - { - throw new ArgumentNullException(nameof(scope)); - } + _ = Throws.IfNull(scope); if (!scope.EndsWith("/.default", true, CultureInfo.InvariantCulture)) { @@ -332,7 +321,6 @@ public Task GetAuthenticationResultForAppAsync( MergedOptions mergedOptions = _tokenAcquisitionHost.GetOptions(authenticationScheme ?? tokenAcquisitionOptions?.AuthenticationOptionsName, out _); - if (string.IsNullOrEmpty(tenant)) { tenant = mergedOptions.TenantId; @@ -820,10 +808,7 @@ private Task GetAuthenticationResultForWebAppWithAccountFr string? userFlow = null, TokenAcquisitionOptions? tokenAcquisitionOptions = null) { - if (scopes == null) - { - throw new ArgumentNullException(nameof(scopes)); - } + _ = Throws.IfNull(scopes); var builder = application .AcquireTokenSilent(scopes.Except(_scopesRequestedByMsal), account) diff --git a/src/Microsoft.Identity.Web.TokenCache/ClaimsPrincipalExtensions.cs b/src/Microsoft.Identity.Web.TokenCache/ClaimsPrincipalExtensions.cs index 3acdcac30..59d79b1d5 100644 --- a/src/Microsoft.Identity.Web.TokenCache/ClaimsPrincipalExtensions.cs +++ b/src/Microsoft.Identity.Web.TokenCache/ClaimsPrincipalExtensions.cs @@ -79,10 +79,7 @@ public static class ClaimsPrincipalExtensions /// A string corresponding to an account identifier as defined in . public static string? GetMsalAccountId(this ClaimsPrincipal claimsPrincipal) { - if (claimsPrincipal == null) - { - throw new ArgumentNullException(nameof(claimsPrincipal)); - } + _ = Throws.IfNull(claimsPrincipal); string? uniqueObjectIdentifier = claimsPrincipal.GetHomeObjectId(); string? uniqueTenantIdentifier = claimsPrincipal.GetHomeTenantId(); @@ -136,10 +133,7 @@ public static class ClaimsPrincipalExtensions /// The domain hint for the identity, or null if it cannot be found. public static string? GetDomainHint(this ClaimsPrincipal claimsPrincipal) { - if (claimsPrincipal == null) - { - throw new ArgumentNullException(nameof(claimsPrincipal)); - } + _ = Throws.IfNull(claimsPrincipal); string? tenantId = GetTenantId(claimsPrincipal); string? domainHint = string.IsNullOrWhiteSpace(tenantId) @@ -207,10 +201,7 @@ public static class ClaimsPrincipalExtensions private static string? GetClaimValue(ClaimsPrincipal? claimsPrincipal, params string[] claimNames) { - if (claimsPrincipal == null) - { - throw new ArgumentNullException(nameof(claimsPrincipal)); - } + _ = Throws.IfNull(claimsPrincipal); for (var i = 0; i < claimNames.Length; i++) { diff --git a/src/Microsoft.Identity.Web.TokenCache/Distributed/DistributedTokenCacheAdapterExtension.cs b/src/Microsoft.Identity.Web.TokenCache/Distributed/DistributedTokenCacheAdapterExtension.cs index 3da02c121..1dfef0567 100644 --- a/src/Microsoft.Identity.Web.TokenCache/Distributed/DistributedTokenCacheAdapterExtension.cs +++ b/src/Microsoft.Identity.Web.TokenCache/Distributed/DistributedTokenCacheAdapterExtension.cs @@ -18,10 +18,7 @@ public static class DistributedTokenCacheAdapterExtension public static IServiceCollection AddDistributedTokenCaches( this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + _ = Throws.IfNull(services); services.AddDistributedMemoryCache(); services.AddSingleton(); diff --git a/src/Microsoft.Identity.Web.TokenCache/Distributed/MsalDistributedTokenCacheAdapter.cs b/src/Microsoft.Identity.Web.TokenCache/Distributed/MsalDistributedTokenCacheAdapter.cs index 7dfde0ac5..c3792de47 100644 --- a/src/Microsoft.Identity.Web.TokenCache/Distributed/MsalDistributedTokenCacheAdapter.cs +++ b/src/Microsoft.Identity.Web.TokenCache/Distributed/MsalDistributedTokenCacheAdapter.cs @@ -50,10 +50,7 @@ public MsalDistributedTokenCacheAdapter( IServiceProvider? serviceProvider = null) : base(GetDataProtector(distributedCacheOptions, serviceProvider), logger) { - if (distributedCacheOptions == null) - { - throw new ArgumentNullException(nameof(distributedCacheOptions)); - } + _ = Throws.IfNull(distributedCacheOptions); _distributedCache = distributedCache; _distributedCacheOptions = distributedCacheOptions.Value; @@ -80,10 +77,7 @@ public MsalDistributedTokenCacheAdapter( IOptions distributedCacheOptions, IServiceProvider? serviceProvider) { - if (distributedCacheOptions == null) - { - throw new ArgumentNullException(nameof(distributedCacheOptions)); - } + _ = Throws.IfNull(distributedCacheOptions); if (serviceProvider != null && distributedCacheOptions.Value.Encrypt) { diff --git a/src/Microsoft.Identity.Web.TokenCache/InMemory/InMemoryTokenCacheProviderExtension.cs b/src/Microsoft.Identity.Web.TokenCache/InMemory/InMemoryTokenCacheProviderExtension.cs index 2a8cf8a8a..60e7934b1 100644 --- a/src/Microsoft.Identity.Web.TokenCache/InMemory/InMemoryTokenCacheProviderExtension.cs +++ b/src/Microsoft.Identity.Web.TokenCache/InMemory/InMemoryTokenCacheProviderExtension.cs @@ -17,10 +17,7 @@ public static class InMemoryTokenCacheProviderExtension public static IServiceCollection AddInMemoryTokenCaches( this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + _ = Throws.IfNull(services); services.AddMemoryCache(); services.AddSingleton(); diff --git a/src/Microsoft.Identity.Web.TokenCache/InMemory/MsalMemoryTokenCacheProvider.cs b/src/Microsoft.Identity.Web.TokenCache/InMemory/MsalMemoryTokenCacheProvider.cs index f1ac96395..1d29b8d5e 100644 --- a/src/Microsoft.Identity.Web.TokenCache/InMemory/MsalMemoryTokenCacheProvider.cs +++ b/src/Microsoft.Identity.Web.TokenCache/InMemory/MsalMemoryTokenCacheProvider.cs @@ -33,10 +33,7 @@ public MsalMemoryTokenCacheProvider( IMemoryCache memoryCache, IOptions cacheOptions) { - if (cacheOptions == null) - { - throw new ArgumentNullException(nameof(cacheOptions)); - } + _ = Throws.IfNull(cacheOptions); _memoryCache = memoryCache; _cacheOptions = cacheOptions.Value; diff --git a/src/Microsoft.Identity.Web.TokenCache/Microsoft.Identity.Web.TokenCache.csproj b/src/Microsoft.Identity.Web.TokenCache/Microsoft.Identity.Web.TokenCache.csproj index 5e8533af8..47065a7a4 100644 --- a/src/Microsoft.Identity.Web.TokenCache/Microsoft.Identity.Web.TokenCache.csproj +++ b/src/Microsoft.Identity.Web.TokenCache/Microsoft.Identity.Web.TokenCache.csproj @@ -34,4 +34,8 @@ + + + + diff --git a/src/Microsoft.Identity.Web.TokenCache/MsalAbstractTokenCacheProvider.cs b/src/Microsoft.Identity.Web.TokenCache/MsalAbstractTokenCacheProvider.cs index 27da0d743..39428662a 100644 --- a/src/Microsoft.Identity.Web.TokenCache/MsalAbstractTokenCacheProvider.cs +++ b/src/Microsoft.Identity.Web.TokenCache/MsalAbstractTokenCacheProvider.cs @@ -47,10 +47,7 @@ protected MsalAbstractTokenCacheProvider(IDataProtector? dataProtector, ILogger< /// Token cache to serialize/deserialize. public void Initialize(ITokenCache tokenCache) { - if (tokenCache == null) - { - throw new ArgumentNullException(nameof(tokenCache)); - } + _ = Throws.IfNull(tokenCache); tokenCache.SetBeforeAccessAsync(OnBeforeAccessAsync); tokenCache.SetAfterAccessAsync(OnAfterAccessAsync); diff --git a/src/Microsoft.Identity.Web.TokenCache/TokenCacheExtensions.cs b/src/Microsoft.Identity.Web.TokenCache/TokenCacheExtensions.cs index 0f71ab6c0..0289b1661 100644 --- a/src/Microsoft.Identity.Web.TokenCache/TokenCacheExtensions.cs +++ b/src/Microsoft.Identity.Web.TokenCache/TokenCacheExtensions.cs @@ -69,8 +69,8 @@ internal static IConfidentialClientApplication AddTokenCaches( this IConfidentialClientApplication confidentialClientApp, Action initializeCaches) { - _ = confidentialClientApp ?? throw new ArgumentNullException(nameof(confidentialClientApp)); - _ = initializeCaches ?? throw new ArgumentNullException(nameof(initializeCaches)); + _ = Throws.IfNull(confidentialClientApp); + _ = Throws.IfNull(initializeCaches); // try to reuse existing XYZ cache if AddXYZCache was called before, to simulate ASP.NET Core var serviceProvider = s_serviceProviderFromAction.GetOrAdd(initializeCaches.Method, _ => @@ -112,7 +112,7 @@ internal static IConfidentialClientApplication AddTokenCaches( public static IConfidentialClientApplication AddInMemoryTokenCache( this IConfidentialClientApplication confidentialClientApp) { - _ = confidentialClientApp ?? throw new ArgumentNullException(nameof(confidentialClientApp)); + _ = Throws.IfNull(confidentialClientApp); confidentialClientApp.AddTokenCaches(services => { @@ -151,8 +151,8 @@ public static IConfidentialClientApplication AddInMemoryTokenCache( this IConfidentialClientApplication confidentialClientApp, Action initializeMemoryCache) { - _ = confidentialClientApp ?? throw new ArgumentNullException(nameof(confidentialClientApp)); - _ = initializeMemoryCache ?? throw new ArgumentNullException(nameof(initializeMemoryCache)); + _ = Throws.IfNull(confidentialClientApp); + _ = Throws.IfNull(initializeMemoryCache); confidentialClientApp.AddTokenCaches(services => { @@ -193,8 +193,8 @@ public static IConfidentialClientApplication AddDistributedTokenCache( this IConfidentialClientApplication confidentialClientApp, Action initializeDistributedCache) { - _ = confidentialClientApp ?? throw new ArgumentNullException(nameof(confidentialClientApp)); - _ = initializeDistributedCache ?? throw new ArgumentNullException(nameof(initializeDistributedCache)); + _ = Throws.IfNull(confidentialClientApp); + _ = Throws.IfNull(initializeDistributedCache); confidentialClientApp.AddTokenCaches(services => { diff --git a/src/Microsoft.Identity.Web.TokenCache/Utility.cs b/src/Microsoft.Identity.Web.TokenCache/Utility.cs index 337276304..bf10a8fdf 100644 --- a/src/Microsoft.Identity.Web.TokenCache/Utility.cs +++ b/src/Microsoft.Identity.Web.TokenCache/Utility.cs @@ -16,10 +16,7 @@ internal static class Utility internal static async Task Measure(this Task task) { - if (task == null) - { - throw new ArgumentNullException(nameof(task)); - } + _ = Throws.IfNull(task); var startTicks = s_watch.Elapsed.Ticks; await task.ConfigureAwait(false); @@ -29,10 +26,7 @@ internal static async Task Measure(this Task task) internal static async Task> Measure(this Task task) { - if (task == null) - { - throw new ArgumentNullException(nameof(task)); - } + _ = Throws.IfNull(task); var startTicks = s_watch.Elapsed.Ticks; var taskResult = await task.ConfigureAwait(false); diff --git a/src/Microsoft.Identity.Web.UI/ServiceCollectionExtensions.cs b/src/Microsoft.Identity.Web.UI/ServiceCollectionExtensions.cs index 6b987ee15..c7a89212a 100644 --- a/src/Microsoft.Identity.Web.UI/ServiceCollectionExtensions.cs +++ b/src/Microsoft.Identity.Web.UI/ServiceCollectionExtensions.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. using System; +using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; @@ -21,10 +22,7 @@ public static class ServiceCollectionExtensions /// MVC builder for chaining. public static IMvcBuilder AddMicrosoftIdentityUI(this IMvcBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + _ = Throws.IfNull(builder); builder.ConfigureApplicationPartManager(apm => { diff --git a/src/Microsoft.Identity.Web/AccountExtensions.cs b/src/Microsoft.Identity.Web/AccountExtensions.cs index 9cb4e8157..bb6cebf6c 100644 --- a/src/Microsoft.Identity.Web/AccountExtensions.cs +++ b/src/Microsoft.Identity.Web/AccountExtensions.cs @@ -20,10 +20,7 @@ public static class AccountExtensions /// A built from . public static ClaimsPrincipal ToClaimsPrincipal(this IAccount account) { - if (account == null) - { - throw new ArgumentNullException(nameof(account)); - } + _ = Throws.IfNull(account); ClaimsIdentity identity = new ClaimsIdentity(new[] { diff --git a/src/Microsoft.Identity.Web/AppServicesAuth/AppServicesAuthenticationBuilderExtensions.cs b/src/Microsoft.Identity.Web/AppServicesAuth/AppServicesAuthenticationBuilderExtensions.cs index 0b0eb4a35..7e3f7a8f6 100644 --- a/src/Microsoft.Identity.Web/AppServicesAuth/AppServicesAuthenticationBuilderExtensions.cs +++ b/src/Microsoft.Identity.Web/AppServicesAuth/AppServicesAuthenticationBuilderExtensions.cs @@ -18,10 +18,7 @@ public static class AppServicesAuthenticationBuilderExtensions public static AuthenticationBuilder AddAppServicesAuthentication( this AuthenticationBuilder builder) { - if (builder is null) - { - throw new System.ArgumentNullException(nameof(builder)); - } + _ = Throws.IfNull(builder); builder.AddScheme( AppServicesAuthenticationDefaults.AuthenticationScheme, diff --git a/src/Microsoft.Identity.Web/AppServicesAuth/AppServicesAuthenticationHandler.cs b/src/Microsoft.Identity.Web/AppServicesAuth/AppServicesAuthenticationHandler.cs index 2e2b4ed16..83235bc47 100644 --- a/src/Microsoft.Identity.Web/AppServicesAuth/AppServicesAuthenticationHandler.cs +++ b/src/Microsoft.Identity.Web/AppServicesAuth/AppServicesAuthenticationHandler.cs @@ -42,7 +42,7 @@ protected override Task HandleAuthenticateAsync() { AuthenticationTicket ticket = new AuthenticationTicket(claimsPrincipal, AppServicesAuthenticationDefaults.AuthenticationScheme); AuthenticateResult success = AuthenticateResult.Success(ticket); - return Task.FromResult(success); + return Task.FromResult(success); } } diff --git a/src/Microsoft.Identity.Web/AppServicesAuth/AppServicesAuthenticationInformation.cs b/src/Microsoft.Identity.Web/AppServicesAuth/AppServicesAuthenticationInformation.cs index 1e6efe677..050de1fda 100644 --- a/src/Microsoft.Identity.Web/AppServicesAuth/AppServicesAuthenticationInformation.cs +++ b/src/Microsoft.Identity.Web/AppServicesAuth/AppServicesAuthenticationInformation.cs @@ -7,6 +7,7 @@ using System.Security.Claims; using Microsoft.Extensions.Primitives; using Microsoft.IdentityModel.JsonWebTokens; +using static Microsoft.Identity.Web.AppServicesAuthenticationTokenAcquisition; namespace Microsoft.Identity.Web { @@ -138,10 +139,7 @@ internal static string? Issuer /// The ID Token. internal static string? GetIdToken(IDictionary headers) { - if (headers is null) - { - throw new ArgumentNullException(nameof(headers)); - } + _ = Throws.IfNull(headers); headers.TryGetValue(AppServicesAuthIdTokenHeader, out var idToken); @@ -161,10 +159,7 @@ internal static string? Issuer /// The IDP. internal static string? GetIdp(IDictionary headers) { - if (headers is null) - { - throw new ArgumentNullException(nameof(headers)); - } + _ = Throws.IfNull(headers); headers.TryGetValue(AppServicesAuthIdpTokenHeader, out var idp); #if DEBUG diff --git a/src/Microsoft.Identity.Web/AppServicesAuth/AppServicesAuthenticationTokenAcquisition.cs b/src/Microsoft.Identity.Web/AppServicesAuth/AppServicesAuthenticationTokenAcquisition.cs index 62c5d605e..c1c0f37c9 100644 --- a/src/Microsoft.Identity.Web/AppServicesAuth/AppServicesAuthenticationTokenAcquisition.cs +++ b/src/Microsoft.Identity.Web/AppServicesAuth/AppServicesAuthenticationTokenAcquisition.cs @@ -68,7 +68,7 @@ public AppServicesAuthenticationTokenAcquisition( IHttpContextAccessor httpContextAccessor, IHttpClientFactory httpClientFactory) { - _httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor)); + _httpContextAccessor = Throws.IfNull(httpContextAccessor); _httpClientFactory = new MsalAspNetCoreHttpClientFactory(httpClientFactory); _tokenCacheProvider = tokenCacheProvider; } @@ -107,10 +107,7 @@ public async Task GetAccessTokenForAppAsync( TokenAcquisitionOptions? tokenAcquisitionOptions = null) { // We could use MSI - if (scope is null) - { - throw new ArgumentNullException(nameof(scope)); - } + _ = Throws.IfNull(scope); var app = GetOrCreateApplication(); AuthenticationResult result = await app.AcquireTokenForClient(new[] { scope }) diff --git a/src/Microsoft.Identity.Web/AzureFunctionsAuthenticationHttpContextExtension.cs b/src/Microsoft.Identity.Web/AzureFunctionsAuthenticationHttpContextExtension.cs index 66b142a3c..22cba6bb1 100644 --- a/src/Microsoft.Identity.Web/AzureFunctionsAuthenticationHttpContextExtension.cs +++ b/src/Microsoft.Identity.Web/AzureFunctionsAuthenticationHttpContextExtension.cs @@ -6,6 +6,7 @@ using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; +using static Microsoft.Identity.Web.AppServicesAuthenticationTokenAcquisition; namespace Microsoft.Identity.Web { @@ -24,10 +25,7 @@ public static class AzureFunctionsAuthenticationHttpContextExtension public static async Task<(bool, IActionResult?)> AuthenticateAzureFunctionAsync( this HttpContext httpContext) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + _ = Throws.IfNull(httpContext); AuthenticateResult result = await httpContext.AuthenticateAsync(Constants.Bearer).ConfigureAwait(false); diff --git a/src/Microsoft.Identity.Web/CookiePolicyOptionsExtensions.cs b/src/Microsoft.Identity.Web/CookiePolicyOptionsExtensions.cs index 74e41acfe..cef950762 100644 --- a/src/Microsoft.Identity.Web/CookiePolicyOptionsExtensions.cs +++ b/src/Microsoft.Identity.Web/CookiePolicyOptionsExtensions.cs @@ -6,6 +6,7 @@ using System.Text.RegularExpressions; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; +using static Microsoft.Identity.Web.AppServicesAuthenticationTokenAcquisition; namespace Microsoft.Identity.Web { @@ -45,10 +46,7 @@ public static CookiePolicyOptions HandleSameSiteCookieCompatibility(this CookieP /// to chain. public static CookiePolicyOptions HandleSameSiteCookieCompatibility(this CookiePolicyOptions options, Func disallowsSameSiteNone) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + _ = Throws.IfNull(options); options.MinimumSameSitePolicy = SameSiteMode.Unspecified; options.OnAppendCookie = cookieContext => diff --git a/src/Microsoft.Identity.Web/DownstreamWebApiSupport/DownstreamWebApiExtensions.cs b/src/Microsoft.Identity.Web/DownstreamWebApiSupport/DownstreamWebApiExtensions.cs index e29de9f20..dec1d0203 100644 --- a/src/Microsoft.Identity.Web/DownstreamWebApiSupport/DownstreamWebApiExtensions.cs +++ b/src/Microsoft.Identity.Web/DownstreamWebApiSupport/DownstreamWebApiExtensions.cs @@ -25,10 +25,7 @@ public static MicrosoftIdentityAppCallsWebApiAuthenticationBuilder AddDownstream string serviceName, IConfiguration configuration) { - if (builder is null) - { - throw new ArgumentNullException(nameof(builder)); - } + _ = Throws.IfNull(builder); builder.Services.Configure(serviceName, configuration); builder.Services.AddHttpClient(); @@ -48,10 +45,7 @@ public static MicrosoftIdentityAppCallsWebApiAuthenticationBuilder AddDownstream string serviceName, Action configureOptions) { - if (builder is null) - { - throw new ArgumentNullException(nameof(builder)); - } + _ = Throws.IfNull(builder); builder.Services.Configure(serviceName, configureOptions); diff --git a/src/Microsoft.Identity.Web/DownstreamWebApiSupport/DownstreamWebApiGenericExtensions.cs b/src/Microsoft.Identity.Web/DownstreamWebApiSupport/DownstreamWebApiGenericExtensions.cs index 221b65950..9d2fa541d 100644 --- a/src/Microsoft.Identity.Web/DownstreamWebApiSupport/DownstreamWebApiGenericExtensions.cs +++ b/src/Microsoft.Identity.Web/DownstreamWebApiSupport/DownstreamWebApiGenericExtensions.cs @@ -7,6 +7,7 @@ using System.Text; using System.Text.Json; using System.Threading.Tasks; +using static Microsoft.Identity.Web.AppServicesAuthenticationTokenAcquisition; namespace Microsoft.Identity.Web { @@ -42,10 +43,7 @@ public static class DownstreamWebApiGenericExtensions string? authenticationScheme = null) where TOutput : class { - if (downstreamWebApi is null) - { - throw new ArgumentNullException(nameof(downstreamWebApi)); - } + _ = Throws.IfNull(downstreamWebApi); HttpResponseMessage response = await downstreamWebApi.CallWebApiForUserAsync( serviceName, @@ -82,10 +80,7 @@ public static async Task GetForUserAsync( ClaimsPrincipal? user = null, string? authenticationScheme = null) { - if (downstreamWebApi is null) - { - throw new ArgumentNullException(nameof(downstreamWebApi)); - } + _ = Throws.IfNull(downstreamWebApi); using StringContent? input = ConvertFromInput(inputData); @@ -128,10 +123,7 @@ await downstreamWebApi.CallWebApiForUserAsync( string? authenticationScheme = null) where TOutput : class { - if (downstreamWebApi is null) - { - throw new ArgumentNullException(nameof(downstreamWebApi)); - } + _ = Throws.IfNull(downstreamWebApi); using StringContent? input = ConvertFromInput(inputData); @@ -173,10 +165,7 @@ public static async Task PutForUserAsync( ClaimsPrincipal? user = null, string? authenticationScheme = null) { - if (downstreamWebApi is null) - { - throw new ArgumentNullException(nameof(downstreamWebApi)); - } + _ = Throws.IfNull(downstreamWebApi); using StringContent? input = ConvertFromInput(inputData); @@ -219,10 +208,7 @@ await downstreamWebApi.CallWebApiForUserAsync( string? authenticationScheme = null) where TOutput : class { - if (downstreamWebApi is null) - { - throw new ArgumentNullException(nameof(downstreamWebApi)); - } + _ = Throws.IfNull(downstreamWebApi); using StringContent? input = ConvertFromInput(inputData); @@ -262,10 +248,7 @@ await downstreamWebApi.CallWebApiForUserAsync( string? authenticationScheme = null) where TOutput : class { - if (downstreamWebApi is null) - { - throw new ArgumentNullException(nameof(downstreamWebApi)); - } + _ = Throws.IfNull(downstreamWebApi); HttpResponseMessage response = await downstreamWebApi.CallWebApiForUserAsync( serviceName, diff --git a/src/Microsoft.Identity.Web/DownstreamWebApiSupport/MicrosoftIdentityAppAuthenticationMessageHandler.cs b/src/Microsoft.Identity.Web/DownstreamWebApiSupport/MicrosoftIdentityAppAuthenticationMessageHandler.cs index ec4b59003..e697da158 100644 --- a/src/Microsoft.Identity.Web/DownstreamWebApiSupport/MicrosoftIdentityAppAuthenticationMessageHandler.cs +++ b/src/Microsoft.Identity.Web/DownstreamWebApiSupport/MicrosoftIdentityAppAuthenticationMessageHandler.cs @@ -33,10 +33,7 @@ public MicrosoftIdentityAppAuthenticationMessageHandler( protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // validate arguments - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } + _ = Throws.IfNull(request); // authenticate var options = GetOptionsForRequest(request); diff --git a/src/Microsoft.Identity.Web/DownstreamWebApiSupport/MicrosoftIdentityAuthenticationBaseMessageHandler.cs b/src/Microsoft.Identity.Web/DownstreamWebApiSupport/MicrosoftIdentityAuthenticationBaseMessageHandler.cs index 5285ef0e7..2452adc84 100644 --- a/src/Microsoft.Identity.Web/DownstreamWebApiSupport/MicrosoftIdentityAuthenticationBaseMessageHandler.cs +++ b/src/Microsoft.Identity.Web/DownstreamWebApiSupport/MicrosoftIdentityAuthenticationBaseMessageHandler.cs @@ -45,10 +45,7 @@ protected MicrosoftIdentityAuthenticationBaseMessageHandler( /// The configured options. protected MicrosoftIdentityAuthenticationMessageHandlerOptions GetOptionsForRequest(HttpRequestMessage request) { - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } + _ = Throws.IfNull(request); var options = _serviceName == null ? _namedMessageHandlerOptions.CurrentValue diff --git a/src/Microsoft.Identity.Web/DownstreamWebApiSupport/MicrosoftIdentityAuthenticationMessageHandlerHttpClientBuilderExtensions.cs b/src/Microsoft.Identity.Web/DownstreamWebApiSupport/MicrosoftIdentityAuthenticationMessageHandlerHttpClientBuilderExtensions.cs index 731d7ef9e..a086a7f4f 100644 --- a/src/Microsoft.Identity.Web/DownstreamWebApiSupport/MicrosoftIdentityAuthenticationMessageHandlerHttpClientBuilderExtensions.cs +++ b/src/Microsoft.Identity.Web/DownstreamWebApiSupport/MicrosoftIdentityAuthenticationMessageHandlerHttpClientBuilderExtensions.cs @@ -26,10 +26,7 @@ public static IHttpClientBuilder AddMicrosoftIdentityUserAuthenticationHandler( string serviceName, IConfiguration configuration) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + _ = Throws.IfNull(builder); builder.Services.Configure(serviceName, configuration); builder.AddMicrosoftIdentityAuthenticationHandlerCore(factory => factory.CreateUserHandler(serviceName)); @@ -49,10 +46,7 @@ public static IHttpClientBuilder AddMicrosoftIdentityUserAuthenticationHandler( string serviceName, Action configureOptions) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + _ = Throws.IfNull(builder); builder.Services.Configure(serviceName, configureOptions); builder.AddMicrosoftIdentityAuthenticationHandlerCore(factory => factory.CreateUserHandler(serviceName)); @@ -72,10 +66,7 @@ public static IHttpClientBuilder AddMicrosoftIdentityAppAuthenticationHandler( string serviceName, IConfiguration configuration) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + _ = Throws.IfNull(builder); builder.Services.Configure(serviceName, configuration); builder.AddMicrosoftIdentityAuthenticationHandlerCore(factory => factory.CreateAppHandler(serviceName)); @@ -95,10 +86,7 @@ public static IHttpClientBuilder AddMicrosoftIdentityAppAuthenticationHandler( string serviceName, Action configureOptions) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + _ = Throws.IfNull(builder); builder.Services.Configure(serviceName, configureOptions); builder.AddMicrosoftIdentityAuthenticationHandlerCore(factory => factory.CreateAppHandler(serviceName)); diff --git a/src/Microsoft.Identity.Web/DownstreamWebApiSupport/MicrosoftIdentityUserAuthenticationMessageHandler.cs b/src/Microsoft.Identity.Web/DownstreamWebApiSupport/MicrosoftIdentityUserAuthenticationMessageHandler.cs index b305d1640..e5a37b61e 100644 --- a/src/Microsoft.Identity.Web/DownstreamWebApiSupport/MicrosoftIdentityUserAuthenticationMessageHandler.cs +++ b/src/Microsoft.Identity.Web/DownstreamWebApiSupport/MicrosoftIdentityUserAuthenticationMessageHandler.cs @@ -38,7 +38,7 @@ public MicrosoftIdentityUserAuthenticationMessageHandler( protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // validate arguments - CheckParameters(request); + _ = Throws.IfNull(request); // authenticate var options = GetOptionsForRequest(request); @@ -69,13 +69,5 @@ protected override async Task SendAsync(HttpRequestMessage return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); } - - private void CheckParameters(HttpRequestMessage request) - { - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } - } } } diff --git a/src/Microsoft.Identity.Web/IncrementalConsentAndConditionalAccessHelper.cs b/src/Microsoft.Identity.Web/IncrementalConsentAndConditionalAccessHelper.cs index eb455d77a..0dd2c5737 100644 --- a/src/Microsoft.Identity.Web/IncrementalConsentAndConditionalAccessHelper.cs +++ b/src/Microsoft.Identity.Web/IncrementalConsentAndConditionalAccessHelper.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Linq; using System.Security.Claims; +using Azure.Core; using Microsoft.AspNetCore.Authentication; using Microsoft.Identity.Client; using Microsoft.IdentityModel.Protocols.OpenIdConnect; @@ -25,10 +26,7 @@ internal static class IncrementalConsentAndConditionalAccessHelper /// the user, and false, otherwise. public static bool CanBeSolvedByReSignInOfUser(MsalUiRequiredException ex) { - if (ex == null) - { - throw new ArgumentNullException(nameof(ex)); - } + _ = Throws.IfNull(ex); // ex.ErrorCode != MsalUiRequiredException.UserNullError indicates a cache problem. // When calling an [Authenticate]-decorated controller we expect an authenticated @@ -52,10 +50,7 @@ public static AuthenticationProperties BuildAuthenticationProperties( ClaimsPrincipal user, string? userflow = null) { - if (ex == null) - { - throw new ArgumentNullException(nameof(ex)); - } + _ = Throws.IfNull(ex); scopes ??= new string[0]; var properties = new AuthenticationProperties(); diff --git a/src/Microsoft.Identity.Web/MicrosoftIdentityCircuitHandler.cs b/src/Microsoft.Identity.Web/MicrosoftIdentityCircuitHandler.cs index ef0a3833a..a376bf9f0 100644 --- a/src/Microsoft.Identity.Web/MicrosoftIdentityCircuitHandler.cs +++ b/src/Microsoft.Identity.Web/MicrosoftIdentityCircuitHandler.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. using System; +using Azure.Core; using Microsoft.AspNetCore.Components.Server.Circuits; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; @@ -22,10 +23,7 @@ public static class MicrosoftIdentityBlazorServiceCollectionExtensions public static IServerSideBlazorBuilder AddMicrosoftIdentityConsentHandler( this IServerSideBlazorBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + _ = Throws.IfNull(builder); builder.Services.TryAddEnumerable(ServiceDescriptor.Scoped()); builder.Services.TryAddScoped(); @@ -41,10 +39,7 @@ public static IServerSideBlazorBuilder AddMicrosoftIdentityConsentHandler( public static IServiceCollection AddMicrosoftIdentityConsentHandler( this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + _ = Throws.IfNull(services); services.TryAddEnumerable(ServiceDescriptor.Scoped()); services.TryAddScoped(); diff --git a/src/Microsoft.Identity.Web/Policy/PolicyBuilderExtensions.cs b/src/Microsoft.Identity.Web/Policy/PolicyBuilderExtensions.cs index 3e5f63a16..1f4bb6056 100644 --- a/src/Microsoft.Identity.Web/Policy/PolicyBuilderExtensions.cs +++ b/src/Microsoft.Identity.Web/Policy/PolicyBuilderExtensions.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using Azure.Core; using Microsoft.AspNetCore.Authorization; namespace Microsoft.Identity.Web @@ -31,10 +32,7 @@ public static AuthorizationPolicyBuilder RequireScope( this AuthorizationPolicyBuilder authorizationPolicyBuilder, params string[] allowedValues) { - if (authorizationPolicyBuilder == null) - { - throw new ArgumentNullException(nameof(authorizationPolicyBuilder)); - } + _ = Throws.IfNull(authorizationPolicyBuilder); return RequireScope(authorizationPolicyBuilder, (IEnumerable)allowedValues); } @@ -50,10 +48,7 @@ public static AuthorizationPolicyBuilder RequireScope( this AuthorizationPolicyBuilder authorizationPolicyBuilder, IEnumerable allowedValues) { - if (authorizationPolicyBuilder == null) - { - throw new ArgumentNullException(nameof(authorizationPolicyBuilder)); - } + _ = Throws.IfNull(authorizationPolicyBuilder); authorizationPolicyBuilder.Requirements.Add(new ScopeAuthorizationRequirement(allowedValues)); return authorizationPolicyBuilder; @@ -72,10 +67,7 @@ public static AuthorizationPolicyBuilder RequireScopeOrAppPermission( IEnumerable allowedScopeValues, IEnumerable allowedAppPermissionValues) { - if (authorizationPolicyBuilder == null) - { - throw new ArgumentNullException(nameof(authorizationPolicyBuilder)); - } + _ = Throws.IfNull(authorizationPolicyBuilder); authorizationPolicyBuilder.Requirements.Add(new ScopeOrAppPermissionAuthorizationRequirement( allowedScopeValues, diff --git a/src/Microsoft.Identity.Web/Policy/RequireScopeOptions.cs b/src/Microsoft.Identity.Web/Policy/RequireScopeOptions.cs index 1b426e138..deb5d013b 100644 --- a/src/Microsoft.Identity.Web/Policy/RequireScopeOptions.cs +++ b/src/Microsoft.Identity.Web/Policy/RequireScopeOptions.cs @@ -29,10 +29,7 @@ public void PostConfigure( string name, AuthorizationOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + _ = Throws.IfNull(options); options.DefaultPolicy = options.DefaultPolicy is null ? _defaultPolicy diff --git a/src/Microsoft.Identity.Web/Policy/RequireScopeOrAppPermissionOptions.cs b/src/Microsoft.Identity.Web/Policy/RequireScopeOrAppPermissionOptions.cs index 787951d26..f0972dac0 100644 --- a/src/Microsoft.Identity.Web/Policy/RequireScopeOrAppPermissionOptions.cs +++ b/src/Microsoft.Identity.Web/Policy/RequireScopeOrAppPermissionOptions.cs @@ -29,10 +29,7 @@ public void PostConfigure( string name, AuthorizationOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + _ = Throws.IfNull(options); options.DefaultPolicy = options.DefaultPolicy is null ? _defaultPolicy diff --git a/src/Microsoft.Identity.Web/Policy/RequiredScopeAttribute.cs b/src/Microsoft.Identity.Web/Policy/RequiredScopeAttribute.cs index 0af35a628..6e10b5887 100644 --- a/src/Microsoft.Identity.Web/Policy/RequiredScopeAttribute.cs +++ b/src/Microsoft.Identity.Web/Policy/RequiredScopeAttribute.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. using System; +using Microsoft.AspNetCore.Authorization; namespace Microsoft.Identity.Web.Resource { @@ -55,7 +56,7 @@ public class RequiredScopeAttribute : Attribute, IAuthRequiredScopeMetadata /// if you want to express the required scopes from the configuration. public RequiredScopeAttribute(params string[] acceptedScopes) { - AcceptedScope = acceptedScopes ?? throw new ArgumentNullException(nameof(acceptedScopes)); + AcceptedScope = Throws.IfNull(acceptedScopes); } /// diff --git a/src/Microsoft.Identity.Web/Policy/RequiredScopeOrAppPermissionAttribute.cs b/src/Microsoft.Identity.Web/Policy/RequiredScopeOrAppPermissionAttribute.cs index de013e86c..17b6cc3e8 100644 --- a/src/Microsoft.Identity.Web/Policy/RequiredScopeOrAppPermissionAttribute.cs +++ b/src/Microsoft.Identity.Web/Policy/RequiredScopeOrAppPermissionAttribute.cs @@ -78,8 +78,8 @@ public class RequiredScopeOrAppPermissionAttribute : Attribute, IAuthRequiredSco /// if you want to express the required scopes or app permissions from the configuration. public RequiredScopeOrAppPermissionAttribute(string[] acceptedScopes, string[] acceptedAppPermissions) { - AcceptedScope = acceptedScopes ?? throw new ArgumentNullException(nameof(acceptedScopes)); - AcceptedAppPermission = acceptedAppPermissions ?? throw new ArgumentNullException(nameof(acceptedAppPermissions)); + AcceptedScope = Throws.IfNull(acceptedScopes); + AcceptedAppPermission = Throws.IfNull(acceptedAppPermissions); } /// diff --git a/src/Microsoft.Identity.Web/Policy/ScopeAuthorizationHandler.cs b/src/Microsoft.Identity.Web/Policy/ScopeAuthorizationHandler.cs index a96f05ff7..8f066d841 100644 --- a/src/Microsoft.Identity.Web/Policy/ScopeAuthorizationHandler.cs +++ b/src/Microsoft.Identity.Web/Policy/ScopeAuthorizationHandler.cs @@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Options; namespace Microsoft.Identity.Web { @@ -38,15 +39,9 @@ protected override Task HandleRequirementAsync( AuthorizationHandlerContext context, ScopeAuthorizationRequirement requirement) { - if (context is null) - { - throw new ArgumentNullException(nameof(context)); - } + _ = Throws.IfNull(context); - if (requirement is null) - { - throw new ArgumentNullException(nameof(requirement)); - } + _ = Throws.IfNull(requirement); // The resource is either the HttpContext or the Endpoint directly when used with the // authorization middleware diff --git a/src/Microsoft.Identity.Web/Policy/ScopeOrAppPermissionAuthorizationHandler.cs b/src/Microsoft.Identity.Web/Policy/ScopeOrAppPermissionAuthorizationHandler.cs index 27bf6ec0c..551fab883 100644 --- a/src/Microsoft.Identity.Web/Policy/ScopeOrAppPermissionAuthorizationHandler.cs +++ b/src/Microsoft.Identity.Web/Policy/ScopeOrAppPermissionAuthorizationHandler.cs @@ -9,6 +9,7 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Options; namespace Microsoft.Identity.Web { @@ -39,15 +40,9 @@ protected override Task HandleRequirementAsync( AuthorizationHandlerContext context, ScopeOrAppPermissionAuthorizationRequirement requirement) { - if (context is null) - { - throw new ArgumentNullException(nameof(context)); - } + _ = Throws.IfNull(context); - if (requirement is null) - { - throw new ArgumentNullException(nameof(requirement)); - } + _ = Throws.IfNull(requirement); // The resource is either the HttpContext or the Endpoint directly when used with the // authorization middleware diff --git a/src/Microsoft.Identity.Web/Resource/RegisterValidAudience.cs b/src/Microsoft.Identity.Web/Resource/RegisterValidAudience.cs index 0c67f654c..3f36b3915 100644 --- a/src/Microsoft.Identity.Web/Resource/RegisterValidAudience.cs +++ b/src/Microsoft.Identity.Web/Resource/RegisterValidAudience.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; +using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; namespace Microsoft.Identity.Web.Resource @@ -21,10 +22,7 @@ public void RegisterAudienceValidation( TokenValidationParameters validationParameters, MicrosoftIdentityOptions microsoftIdentityOptions) { - if (validationParameters == null) - { - throw new ArgumentNullException(nameof(validationParameters)); - } + _ = Throws.IfNull(validationParameters); ClientId = microsoftIdentityOptions.ClientId; IsB2C = microsoftIdentityOptions.IsB2C; diff --git a/src/Microsoft.Identity.Web/Resource/RolesRequiredHttpContextExtensions.cs b/src/Microsoft.Identity.Web/Resource/RolesRequiredHttpContextExtensions.cs index 79ad48137..6ffdf7517 100644 --- a/src/Microsoft.Identity.Web/Resource/RolesRequiredHttpContextExtensions.cs +++ b/src/Microsoft.Identity.Web/Resource/RolesRequiredHttpContextExtensions.cs @@ -9,6 +9,7 @@ using System.Net.Http; using System.Security.Claims; using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Options; namespace Microsoft.Identity.Web.Resource { @@ -28,15 +29,9 @@ public static class RolesRequiredHttpContextExtensions /// because the app does not have the expected roles. public static void ValidateAppRole(this HttpContext context, params string[] acceptedRoles) { - if (acceptedRoles == null) - { - throw new ArgumentNullException(nameof(acceptedRoles)); - } + _ = Throws.IfNull(acceptedRoles); - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + _ = Throws.IfNull(context); IEnumerable userClaims; ClaimsPrincipal user; diff --git a/src/Microsoft.Identity.Web/Resource/ScopesRequiredHttpContextExtensions.cs b/src/Microsoft.Identity.Web/Resource/ScopesRequiredHttpContextExtensions.cs index bb533feca..56fa022e0 100644 --- a/src/Microsoft.Identity.Web/Resource/ScopesRequiredHttpContextExtensions.cs +++ b/src/Microsoft.Identity.Web/Resource/ScopesRequiredHttpContextExtensions.cs @@ -9,6 +9,7 @@ using System.Net.Http; using System.Security.Claims; using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Options; namespace Microsoft.Identity.Web.Resource { @@ -35,15 +36,9 @@ public static class ScopesRequiredHttpContextExtensions /// Scopes accepted by this web API. public static void VerifyUserHasAnyAcceptedScope(this HttpContext context, params string[] acceptedScopes) { - if (acceptedScopes == null) - { - throw new ArgumentNullException(nameof(acceptedScopes)); - } + _ = Throws.IfNull(acceptedScopes); - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + _ = Throws.IfNull(context); IEnumerable userClaims; ClaimsPrincipal user; diff --git a/src/Microsoft.Identity.Web/TokenCacheProviders/Session/SessionTokenCacheProviderExtension.cs b/src/Microsoft.Identity.Web/TokenCacheProviders/Session/SessionTokenCacheProviderExtension.cs index 014e0639a..ca31cb372 100644 --- a/src/Microsoft.Identity.Web/TokenCacheProviders/Session/SessionTokenCacheProviderExtension.cs +++ b/src/Microsoft.Identity.Web/TokenCacheProviders/Session/SessionTokenCacheProviderExtension.cs @@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Options; namespace Microsoft.Identity.Web.TokenCacheProviders.Session { @@ -69,10 +70,7 @@ public static IServiceCollection AddSessionPerUserTokenCache(this IServiceCollec private static IServiceCollection CreateSessionTokenCache(IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + _ = Throws.IfNull(services); services.AddHttpContextAccessor(); services.AddSession(option => diff --git a/src/Microsoft.Identity.Web/WebApiExtensions/MicrosoftIdentityWebApiAuthenticationBuilder.cs b/src/Microsoft.Identity.Web/WebApiExtensions/MicrosoftIdentityWebApiAuthenticationBuilder.cs index e16cf2103..7df685320 100644 --- a/src/Microsoft.Identity.Web/WebApiExtensions/MicrosoftIdentityWebApiAuthenticationBuilder.cs +++ b/src/Microsoft.Identity.Web/WebApiExtensions/MicrosoftIdentityWebApiAuthenticationBuilder.cs @@ -6,7 +6,6 @@ using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Options; using Microsoft.Identity.Client; using Microsoft.Identity.Web.Internal; @@ -36,28 +35,14 @@ internal MicrosoftIdentityWebApiAuthenticationBuilder( : base(services, configurationSection) { JwtBearerAuthenticationScheme = jwtBearerAuthenticationScheme; - ConfigureJwtBearerOptions = configureJwtBearerOptions; - ConfigureMicrosoftIdentityOptions = configureMicrosoftIdentityOptions; - - if (ConfigureMicrosoftIdentityOptions == null) - { - throw new ArgumentNullException(nameof(configureMicrosoftIdentityOptions)); - } - - if (ConfigureJwtBearerOptions == null) - { - throw new ArgumentNullException(nameof(configureMicrosoftIdentityOptions)); - } + _ = Throws.IfNull(configureJwtBearerOptions); + _ = Throws.IfNull(configureMicrosoftIdentityOptions); Services.Configure(jwtBearerAuthenticationScheme, configureMicrosoftIdentityOptions); } - private Action ConfigureMicrosoftIdentityOptions { get; set; } - private string JwtBearerAuthenticationScheme { get; set; } - private Action ConfigureJwtBearerOptions { get; set; } - /// /// Protects the web API with Microsoft identity platform (formerly Azure AD v2.0). /// @@ -66,10 +51,7 @@ internal MicrosoftIdentityWebApiAuthenticationBuilder( public MicrosoftIdentityAppCallsWebApiAuthenticationBuilder EnableTokenAcquisitionToCallDownstreamApi( Action configureConfidentialClientApplicationOptions) { - if (configureConfidentialClientApplicationOptions == null) - { - throw new ArgumentNullException(nameof(configureConfidentialClientApplicationOptions)); - } + _ = Throws.IfNull(configureConfidentialClientApplicationOptions); CallsWebApiImplementation( Services, diff --git a/src/Microsoft.Identity.Web/WebApiExtensions/MicrosoftIdentityWebApiAuthenticationBuilderExtensions.cs b/src/Microsoft.Identity.Web/WebApiExtensions/MicrosoftIdentityWebApiAuthenticationBuilderExtensions.cs index c4e57700b..ffb5a3fa0 100644 --- a/src/Microsoft.Identity.Web/WebApiExtensions/MicrosoftIdentityWebApiAuthenticationBuilderExtensions.cs +++ b/src/Microsoft.Identity.Web/WebApiExtensions/MicrosoftIdentityWebApiAuthenticationBuilderExtensions.cs @@ -41,15 +41,8 @@ public static MicrosoftIdentityWebApiAuthenticationBuilderWithConfiguration AddM string jwtBearerScheme = JwtBearerDefaults.AuthenticationScheme, bool subscribeToJwtBearerMiddlewareDiagnosticsEvents = false) { - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration)); - } - - if (configSectionName == null) - { - throw new ArgumentNullException(nameof(configSectionName)); - } + _ = Throws.IfNull(configuration); + _ = Throws.IfNull(configSectionName); IConfigurationSection configurationSection = configuration.GetSection(configSectionName); @@ -76,15 +69,8 @@ public static MicrosoftIdentityWebApiAuthenticationBuilderWithConfiguration AddM string jwtBearerScheme = JwtBearerDefaults.AuthenticationScheme, bool subscribeToJwtBearerMiddlewareDiagnosticsEvents = false) { - if (configurationSection == null) - { - throw new ArgumentNullException(nameof(configurationSection)); - } - - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + _ = Throws.IfNull(configurationSection); + _ = Throws.IfNull(builder); AddMicrosoftIdentityWebApiImplementation( builder, @@ -118,20 +104,9 @@ public static MicrosoftIdentityWebApiAuthenticationBuilder AddMicrosoftIdentityW string jwtBearerScheme = JwtBearerDefaults.AuthenticationScheme, bool subscribeToJwtBearerMiddlewareDiagnosticsEvents = false) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (configureJwtBearerOptions == null) - { - throw new ArgumentNullException(nameof(configureJwtBearerOptions)); - } - - if (configureMicrosoftIdentityOptions == null) - { - throw new ArgumentNullException(nameof(configureMicrosoftIdentityOptions)); - } + _ = Throws.IfNull(builder); + _ = Throws.IfNull(configureJwtBearerOptions); + _ = Throws.IfNull(configureMicrosoftIdentityOptions); AddMicrosoftIdentityWebApiImplementation( builder, diff --git a/src/Microsoft.Identity.Web/WebApiExtensions/MicrosoftIdentityWebApiAuthenticationBuilderWithConfiguration.cs b/src/Microsoft.Identity.Web/WebApiExtensions/MicrosoftIdentityWebApiAuthenticationBuilderWithConfiguration.cs index cc38429c7..56baa7f56 100644 --- a/src/Microsoft.Identity.Web/WebApiExtensions/MicrosoftIdentityWebApiAuthenticationBuilderWithConfiguration.cs +++ b/src/Microsoft.Identity.Web/WebApiExtensions/MicrosoftIdentityWebApiAuthenticationBuilderWithConfiguration.cs @@ -21,10 +21,7 @@ internal MicrosoftIdentityWebApiAuthenticationBuilderWithConfiguration( IConfigurationSection? configurationSection) : base(services, jwtBearerAuthenticationScheme, configureJwtBearerOptions, configureMicrosoftIdentityOptions, configurationSection) { - if (configurationSection == null) - { - throw new ArgumentNullException(nameof(configurationSection)); - } + _ = Throws.IfNull(configurationSection); } /// diff --git a/src/Microsoft.Identity.Web/WebAppExtensions/MicrosoftIdentityAppCallingWebApiAuthenticationBuilderExt.cs b/src/Microsoft.Identity.Web/WebAppExtensions/MicrosoftIdentityAppCallingWebApiAuthenticationBuilderExt.cs index 140bf89b7..79ec15d34 100644 --- a/src/Microsoft.Identity.Web/WebAppExtensions/MicrosoftIdentityAppCallingWebApiAuthenticationBuilderExt.cs +++ b/src/Microsoft.Identity.Web/WebAppExtensions/MicrosoftIdentityAppCallingWebApiAuthenticationBuilderExt.cs @@ -25,10 +25,7 @@ public static class MicrosoftIdentityAppCallsWebApiAuthenticationBuilderExtensio /// The service collection public static IServiceCollection AddSessionTokenCaches(this MicrosoftIdentityAppCallsWebApiAuthenticationBuilder builder) { - if (builder is null) - { - throw new ArgumentNullException(nameof(builder)); - } + _ = Throws.IfNull(builder); // Add session if you are planning to use session based token cache var sessionStoreService = builder.Services.FirstOrDefault(x => x.ServiceType.Name == Constants.ISessionStore); diff --git a/src/Microsoft.Identity.Web/WebAppExtensions/MicrosoftIdentityWebAppAuthenticationBuilder.cs b/src/Microsoft.Identity.Web/WebAppExtensions/MicrosoftIdentityWebAppAuthenticationBuilder.cs index af77259ab..34fe5e7d1 100644 --- a/src/Microsoft.Identity.Web/WebAppExtensions/MicrosoftIdentityWebAppAuthenticationBuilder.cs +++ b/src/Microsoft.Identity.Web/WebAppExtensions/MicrosoftIdentityWebAppAuthenticationBuilder.cs @@ -35,12 +35,7 @@ internal MicrosoftIdentityWebAppAuthenticationBuilder( : base(services, configurationSection) { OpenIdConnectScheme = openIdConnectScheme; - ConfigureMicrosoftIdentityOptions = configureMicrosoftIdentityOptions; - - if (ConfigureMicrosoftIdentityOptions == null) - { - throw new ArgumentNullException(nameof(configureMicrosoftIdentityOptions)); - } + ConfigureMicrosoftIdentityOptions = Throws.IfNull(configureMicrosoftIdentityOptions); } private Action ConfigureMicrosoftIdentityOptions { get; set; } diff --git a/src/Microsoft.Identity.Web/WebAppExtensions/MicrosoftIdentityWebAppAuthenticationBuilderExtensions.cs b/src/Microsoft.Identity.Web/WebAppExtensions/MicrosoftIdentityWebAppAuthenticationBuilderExtensions.cs index 42a9c6f80..d35db3bb3 100644 --- a/src/Microsoft.Identity.Web/WebAppExtensions/MicrosoftIdentityWebAppAuthenticationBuilderExtensions.cs +++ b/src/Microsoft.Identity.Web/WebAppExtensions/MicrosoftIdentityWebAppAuthenticationBuilderExtensions.cs @@ -84,15 +84,8 @@ public static MicrosoftIdentityWebAppAuthenticationBuilderWithConfiguration AddM bool subscribeToOpenIdConnectMiddlewareDiagnosticsEvents = false, string? displayName = null) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (configurationSection == null) - { - throw new ArgumentException(nameof(configurationSection)); - } + _ = Throws.IfNull(builder); + _ = Throws.IfNull(configurationSection); return builder.AddMicrosoftIdentityWebAppWithConfiguration( options => configurationSection.Bind(options), @@ -124,10 +117,7 @@ public static MicrosoftIdentityWebAppAuthenticationBuilder AddMicrosoftIdentityW bool subscribeToOpenIdConnectMiddlewareDiagnosticsEvents = false, string? displayName = null) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + _ = Throws.IfNull(builder); return builder.AddMicrosoftWebAppWithoutConfiguration( configureMicrosoftIdentityOptions, @@ -229,15 +219,8 @@ private static void AddMicrosoftIdentityWebAppInternal( bool subscribeToOpenIdConnectMiddlewareDiagnosticsEvents, string? displayName) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (configureMicrosoftIdentityOptions == null) - { - throw new ArgumentNullException(nameof(configureMicrosoftIdentityOptions)); - } + _ = Throws.IfNull(builder); + _ = Throws.IfNull(configureMicrosoftIdentityOptions); if (builder.Services.FirstOrDefault(s => s.ImplementationType == typeof(MicrosoftIdentityOptionsMerger)) == null) { diff --git a/src/Microsoft.Identity.Web/WebAppExtensions/MicrosoftIdentityWebAppAuthenticationBuilderWithConfiguration.cs b/src/Microsoft.Identity.Web/WebAppExtensions/MicrosoftIdentityWebAppAuthenticationBuilderWithConfiguration.cs index 9e4be0c16..739590a78 100644 --- a/src/Microsoft.Identity.Web/WebAppExtensions/MicrosoftIdentityWebAppAuthenticationBuilderWithConfiguration.cs +++ b/src/Microsoft.Identity.Web/WebAppExtensions/MicrosoftIdentityWebAppAuthenticationBuilderWithConfiguration.cs @@ -29,10 +29,7 @@ internal MicrosoftIdentityWebAppAuthenticationBuilderWithConfiguration( IConfigurationSection configurationSection) : base(services, openIdConnectScheme, configureMicrosoftIdentityOptions, configurationSection) { - if (configurationSection == null) - { - throw new ArgumentNullException(nameof(configurationSection)); - } + _ = Throws.IfNull(configurationSection); } ///