diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml
deleted file mode 100644
index ea59041bc5..0000000000
--- a/.github/workflows/codeql-analysis.yml
+++ /dev/null
@@ -1,60 +0,0 @@
-name: "CodeQL"
-
-on:
- push:
- branches: [ "dev", "dev7x" ]
- pull_request:
- types:
- - opened
- - synchronize
- - reopened
- - ready_for_review
- branches: [ "dev", "dev7x" ]
-
-jobs:
- analyze:
- name: Analyze
- runs-on: 'ubuntu-latest'
-
- strategy:
- matrix:
- language: [ 'csharp' ]
-
- steps:
- - name: Checkout repository
- uses: actions/checkout@v3
- with:
- fetch-depth: 2
-
- # Initializes the CodeQL tools for scanning.
- - name: Initialize CodeQL
- uses: github/codeql-action/init@v2
- with:
- languages: ${{ matrix.language }}
- # If you wish to specify custom queries, you can do so here or in a config file.
- # By default, queries listed here will override any specified in a config file.
- # Prefix the list here with "+" to use these queries and those in the config file.
-
- # For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
- # queries: security-extended,security-and-quality
-
-
- # Autobuild attempts to build any compiled languages (C/C++, C#, Go, Java, or Swift).
- # If this step fails, then you should remove it and run the build manually (see below)
- - name: Autobuild
- uses: github/codeql-action/autobuild@v2
-
- # ℹ️ Command-line programs to run using the OS shell.
- # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
-
- # If the Autobuild fails above, remove it and uncomment the following three lines.
- # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
-
- # - run: |
- # echo "Run, Build Application using script"
- # ./location_of_script_within_repo/buildscript.sh
-
- - name: Perform CodeQL Analysis
- uses: github/codeql-action/analyze@v2
- with:
- category: "/language:${{matrix.language}}"
diff --git a/Wilson.sln b/Wilson.sln
index 33c8882f25..d4c87853cc 100644
--- a/Wilson.sln
+++ b/Wilson.sln
@@ -60,12 +60,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.IdentityModel.Tes
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.IdentityModel.Logging", "src\Microsoft.IdentityModel.Logging\Microsoft.IdentityModel.Logging.csproj", "{E4E6D0ED-12CB-4C01-A4C1-4F60D10E2304}"
EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "CrossVersionTokenValidation.Test", "CrossVersionTokenValidation.Test", "{310A34D3-8685-4355-8590-84351B5223BC}"
-EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.IdentityModel.JsonWebTokens", "src\Microsoft.IdentityModel.JsonWebTokens\Microsoft.IdentityModel.JsonWebTokens.csproj", "{DBF58792-25DF-4B6E-866C-77A0BC5AB81B}"
EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CrossVersionTokenValidation.Tests", "test\CrossVersionTokenValidation.Tests\CrossVersionTokenValidation.Tests.csproj", "{7E7CCB59-541E-48DA-9044-2D6C4AD8E509}"
-EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Extensions", "Extensions", "{EB14B99B-2255-45BC-BF14-E488DCD4A4BA}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Extensions", "Extensions", "{B961CF69-0DE6-4B9F-9473-9F669365BD62}"
@@ -187,10 +183,6 @@ Global
{DBF58792-25DF-4B6E-866C-77A0BC5AB81B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DBF58792-25DF-4B6E-866C-77A0BC5AB81B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DBF58792-25DF-4B6E-866C-77A0BC5AB81B}.Release|Any CPU.Build.0 = Release|Any CPU
- {7E7CCB59-541E-48DA-9044-2D6C4AD8E509}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {7E7CCB59-541E-48DA-9044-2D6C4AD8E509}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {7E7CCB59-541E-48DA-9044-2D6C4AD8E509}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {7E7CCB59-541E-48DA-9044-2D6C4AD8E509}.Release|Any CPU.Build.0 = Release|Any CPU
{987772FA-BA24-4EF4-9B58-3DA78FFD61DD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{987772FA-BA24-4EF4-9B58-3DA78FFD61DD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{987772FA-BA24-4EF4-9B58-3DA78FFD61DD}.Release|Any CPU.ActiveCfg = Release|Any CPU
@@ -274,9 +266,7 @@ Global
{BDB0A526-FA17-44CF-80D6-4A64F7E6CD7E} = {8905D2E3-4499-4A86-BF3E-F098F228DD59}
{3C338E2D-C1D8-4517-8C52-A86A9F0C8281} = {8905D2E3-4499-4A86-BF3E-F098F228DD59}
{E4E6D0ED-12CB-4C01-A4C1-4F60D10E2304} = {BD2706C5-6C57-484D-89C8-A0CF5F8E3D19}
- {310A34D3-8685-4355-8590-84351B5223BC} = {8905D2E3-4499-4A86-BF3E-F098F228DD59}
{DBF58792-25DF-4B6E-866C-77A0BC5AB81B} = {BD2706C5-6C57-484D-89C8-A0CF5F8E3D19}
- {7E7CCB59-541E-48DA-9044-2D6C4AD8E509} = {310A34D3-8685-4355-8590-84351B5223BC}
{EB14B99B-2255-45BC-BF14-E488DCD4A4BA} = {BD2706C5-6C57-484D-89C8-A0CF5F8E3D19}
{B961CF69-0DE6-4B9F-9473-9F669365BD62} = {8905D2E3-4499-4A86-BF3E-F098F228DD59}
{987772FA-BA24-4EF4-9B58-3DA78FFD61DD} = {B961CF69-0DE6-4B9F-9473-9F669365BD62}
diff --git a/build/CodeCoverage.runsettings b/build/CodeCoverage.runsettings
new file mode 100644
index 0000000000..68c61eff5e
--- /dev/null
+++ b/build/CodeCoverage.runsettings
@@ -0,0 +1,49 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ .*\microsoft.identitymodel.abstractions.dll
+ .*\microsoft.identitymodel.jsonwebtokens.dll
+ .*\microsoft.identitymodel.keyvaultextensions.dll
+ .*\microsoft.identitymodel.logging.dll
+ .*\microsoft.identitymodel.loggingextensions.dll
+ .*\microsoft.identitymodel.managedkeyvaultsecuritykey.dll
+ .*\microsoft.identitymodel.protocols.openidconnect.dll
+ .*\microsoft.identitymodel.protocols.signedhttprequest.dll
+ .*\microsoft.identitymodel.protocols.wsfederation.dll
+ .*\microsoft.identitymodel.protocols.dll
+ .*\microsoft.identitymodel.testextensions.dll
+ .*\microsoft.identitymodel.tokens.saml.dll
+ .*\microsoft.identitymodel.tokens.dll
+ .*\microsoft.identitymodel.validators.dll
+ .*\microsoft.identitymodel.xml.dll
+ .*\system.identitymodel.tokens.jwt.dll
+
+
+
+
+
+
+
+
+
diff --git a/build/common.props b/build/common.props
index 92041e112e..7436651398 100644
--- a/build/common.props
+++ b/build/common.props
@@ -1,4 +1,5 @@
+
@@ -31,7 +32,7 @@
$(SrcTargets)
$(SrcStandardTargets)
$(NetStandardVersion)
- latest
+ 7.3
@@ -47,4 +48,8 @@
+
+
+
+
diff --git a/build/commonTest.props b/build/commonTest.props
index c63ac85e2d..ee3387d6d9 100644
--- a/build/commonTest.props
+++ b/build/commonTest.props
@@ -34,6 +34,7 @@
+
diff --git a/build/dependencies.props b/build/dependencies.props
index 0f2dd00964..23e1b91065 100644
--- a/build/dependencies.props
+++ b/build/dependencies.props
@@ -7,9 +7,11 @@
4.5.0
1.0.0
2.0.3
+ 13.0.3
+ 4.5.5
4.5.0
- 4.7.2
4.7.2
+ 4.7.2
diff --git a/build/dependenciesTest.props b/build/dependenciesTest.props
index 3339d4c31f..0e9cbbac43 100644
--- a/build/dependenciesTest.props
+++ b/build/dependenciesTest.props
@@ -1,12 +1,12 @@
2.1.30
- 2.0.3
2.0.5
2.4.0-prerelease-63213-02
- 1.0.4.403061554
16.10.0
- 4.0.4.403061554
+ 2.0.3
+ 13.0.3
+ 4.3.0
2.4.0
-
\ No newline at end of file
+
diff --git a/buildConfiguration.xml b/buildConfiguration.xml
index 4f1b6a9bb0..85116e6249 100644
--- a/buildConfiguration.xml
+++ b/buildConfiguration.xml
@@ -24,7 +24,6 @@
-
diff --git a/src/Microsoft.IdentityModel.Abstractions/ITelemetryClient.cs b/src/Microsoft.IdentityModel.Abstractions/ITelemetryClient.cs
index e54bb135ec..b6086bec89 100644
--- a/src/Microsoft.IdentityModel.Abstractions/ITelemetryClient.cs
+++ b/src/Microsoft.IdentityModel.Abstractions/ITelemetryClient.cs
@@ -68,11 +68,11 @@ void TrackEvent(
/// Key value pair of Guids to long with the event.
void TrackEvent(
string eventName,
- IDictionary? stringProperties = null,
- IDictionary? longProperties = null,
- IDictionary? boolProperties = null,
- IDictionary? dateTimeProperties = null,
- IDictionary? doubleProperties = null,
- IDictionary? guidProperties = null);
+ IDictionary stringProperties = null,
+ IDictionary longProperties = null,
+ IDictionary boolProperties = null,
+ IDictionary dateTimeProperties = null,
+ IDictionary doubleProperties = null,
+ IDictionary guidProperties = null);
}
}
diff --git a/src/Microsoft.IdentityModel.Abstractions/LogEntry.cs b/src/Microsoft.IdentityModel.Abstractions/LogEntry.cs
index 695ce4e77c..c872bfb707 100644
--- a/src/Microsoft.IdentityModel.Abstractions/LogEntry.cs
+++ b/src/Microsoft.IdentityModel.Abstractions/LogEntry.cs
@@ -16,7 +16,7 @@ public class LogEntry
///
/// Message to be logged.
///
- public string? Message { get; set; }
+ public string Message { get; set; }
///
/// A unique identifier for a request that can help with diagnostics across components.
@@ -24,6 +24,6 @@ public class LogEntry
///
/// Also referred to as ActivityId in Microsoft.IdentityModel.Tokens.CallContext.
///
- public string? CorrelationId { get; set; }
+ public string CorrelationId { get; set; }
}
}
diff --git a/src/Microsoft.IdentityModel.Abstractions/Microsoft.IdentityModel.Abstractions.csproj b/src/Microsoft.IdentityModel.Abstractions/Microsoft.IdentityModel.Abstractions.csproj
index b804ef69b9..be1e21a56c 100644
--- a/src/Microsoft.IdentityModel.Abstractions/Microsoft.IdentityModel.Abstractions.csproj
+++ b/src/Microsoft.IdentityModel.Abstractions/Microsoft.IdentityModel.Abstractions.csproj
@@ -9,7 +9,6 @@
Microsoft.IdentityModel.Abstractions
.NET;Windows;Authentication;Identity;Abstractions
true
- enable
diff --git a/src/Microsoft.IdentityModel.Abstractions/NullTelemetryClient.cs b/src/Microsoft.IdentityModel.Abstractions/NullTelemetryClient.cs
index 5acc0a15d8..3350d6b56a 100644
--- a/src/Microsoft.IdentityModel.Abstractions/NullTelemetryClient.cs
+++ b/src/Microsoft.IdentityModel.Abstractions/NullTelemetryClient.cs
@@ -25,9 +25,7 @@ public class NullTelemetryClient : ITelemetryClient
///
/// Private constructor to prevent the default constructor being exposed.
///
-#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
private NullTelemetryClient() { }
-#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
///
public bool IsEnabled() => false;
@@ -50,12 +48,12 @@ public void TrackEvent(TelemetryEventDetails eventDetails)
///
public void TrackEvent(
string eventName,
- IDictionary? stringProperties = null,
- IDictionary? longProperties = null,
- IDictionary? boolProperties = null,
- IDictionary? dateTimeProperties = null,
- IDictionary? doubleProperties = null,
- IDictionary? guidProperties = null)
+ IDictionary stringProperties = null,
+ IDictionary longProperties = null,
+ IDictionary boolProperties = null,
+ IDictionary dateTimeProperties = null,
+ IDictionary doubleProperties = null,
+ IDictionary guidProperties = null)
{
// no-op
}
diff --git a/src/Microsoft.IdentityModel.Abstractions/TelemetryEventDetails.cs b/src/Microsoft.IdentityModel.Abstractions/TelemetryEventDetails.cs
index 58ee348fb4..86972aaa39 100644
--- a/src/Microsoft.IdentityModel.Abstractions/TelemetryEventDetails.cs
+++ b/src/Microsoft.IdentityModel.Abstractions/TelemetryEventDetails.cs
@@ -23,7 +23,7 @@ public abstract class TelemetryEventDetails
///
/// Name of the telemetry event, should be unique between events.
///
- public virtual string? Name { get; set; }
+ public virtual string Name { get; set; }
///
/// Properties which describe the event.
diff --git a/src/Microsoft.IdentityModel.JsonWebTokens/Json/JsonClaimSet.cs b/src/Microsoft.IdentityModel.JsonWebTokens/Json/JsonClaimSet.cs
index a2173bcf22..0bc088014c 100644
--- a/src/Microsoft.IdentityModel.JsonWebTokens/Json/JsonClaimSet.cs
+++ b/src/Microsoft.IdentityModel.JsonWebTokens/Json/JsonClaimSet.cs
@@ -6,9 +6,9 @@
using System.Globalization;
using System.Security.Claims;
using System.Text.Json;
-using Microsoft.IdentityModel.Json.Linq;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
+using Newtonsoft.Json.Linq;
namespace Microsoft.IdentityModel.JsonWebTokens
{
@@ -22,17 +22,20 @@ internal class JsonClaimSet
internal JsonClaimSet(JsonDocument jsonDocument)
{
- RootElement = jsonDocument.RootElement;
+ // This method is assuming ownership of the JsonDocument, which is backed by one or more ArrayPool arrays.
+ // We need to dispose of it to avoid leaking arrays from the pool. To achieve that, we clone the root element,
+ // which will result in a new JsonElement being created that's not tied to the original and that's not backed by
+ // ArrayPool memory, after which point we can dispose of the original to return the array(s) to the pool.
+ RootElement = jsonDocument.RootElement.Clone();
+ jsonDocument.Dispose();
}
- internal JsonClaimSet(byte[] jsonBytes)
+ internal JsonClaimSet(byte[] jsonBytes) : this(JsonDocument.Parse(jsonBytes))
{
- RootElement = JsonDocument.Parse(jsonBytes).RootElement;
}
- internal JsonClaimSet(string json)
+ internal JsonClaimSet(string json) : this(JsonDocument.Parse(json))
{
- RootElement = JsonDocument.Parse(json).RootElement;
}
internal JsonElement RootElement { get; }
@@ -230,7 +233,7 @@ internal DateTime GetDateTime(string key)
if (!RootElement.TryGetProperty(key, out JsonElement jsonElement))
return DateTime.MinValue;
- return EpochTime.DateTime(Convert.ToInt64(Math.Truncate(Convert.ToDouble(ParseTimeValue(key, jsonElement), CultureInfo.InvariantCulture))));
+ return EpochTime.DateTime(Convert.ToInt64(Math.Truncate((double)ParseTimeValue(key, jsonElement))));
}
internal T GetValue(string key)
diff --git a/src/Microsoft.IdentityModel.JsonWebTokens/JsonWebToken.cs b/src/Microsoft.IdentityModel.JsonWebTokens/JsonWebToken.cs
index 8885a8addb..e9b15adab1 100644
--- a/src/Microsoft.IdentityModel.JsonWebTokens/JsonWebToken.cs
+++ b/src/Microsoft.IdentityModel.JsonWebTokens/JsonWebToken.cs
@@ -605,9 +605,10 @@ public IEnumerable Audiences
if (Payload.TryGetValue(JwtRegisteredClaimNames.Aud, out JsonElement audiences))
{
if (audiences.ValueKind == JsonValueKind.String)
- _audiences = new List { audiences.GetString() };
-
- if (audiences.ValueKind == JsonValueKind.Array)
+ {
+ _audiences.Add(audiences.GetString());
+ }
+ else if (audiences.ValueKind == JsonValueKind.Array)
{
foreach (JsonElement jsonElement in audiences.EnumerateArray())
_audiences.Add(jsonElement.ToString());
diff --git a/src/Microsoft.IdentityModel.JsonWebTokens/JsonWebTokenHandler.cs b/src/Microsoft.IdentityModel.JsonWebTokens/JsonWebTokenHandler.cs
index 911a4575d9..60795b86ad 100644
--- a/src/Microsoft.IdentityModel.JsonWebTokens/JsonWebTokenHandler.cs
+++ b/src/Microsoft.IdentityModel.JsonWebTokens/JsonWebTokenHandler.cs
@@ -4,16 +4,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
-using System.Net;
using System.Security.Claims;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
-using Microsoft.IdentityModel.Json;
-using Microsoft.IdentityModel.Json.Linq;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
+using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
using TokenLogMessages = Microsoft.IdentityModel.Tokens.LogMessages;
namespace Microsoft.IdentityModel.JsonWebTokens
@@ -163,17 +162,28 @@ public virtual bool CanReadToken(string token)
return false;
}
- // Set the maximum number of segments to MaxJwtSegmentCount + 1. This controls the number of splits and allows detecting the number of segments is too large.
- // For example: "a.b.c.d.e.f.g.h" => [a], [b], [c], [d], [e], [f.g.h]. 6 segments.
- // If just MaxJwtSegmentCount was used, then [a], [b], [c], [d], [e.f.g.h] would be returned. 5 segments.
- int tokenPartCount = JwtTokenUtilities.CountJwtTokenPart(token, JwtConstants.MaxJwtSegmentCount + 1);
- if (tokenPartCount == JwtConstants.JwsSegmentCount)
- return JwtTokenUtilities.RegexJws.IsMatch(token);
- else if (tokenPartCount == JwtConstants.JweSegmentCount)
- return JwtTokenUtilities.RegexJwe.IsMatch(token);
-
- LogHelper.LogInformation(LogMessages.IDX14107);
- return false;
+ // Count the number of segments, which is the number of periods + 1. We can stop when we've encountered
+ // more segments than the maximum we know how to handle.
+ int pos = 0;
+ int segmentCount = 1; // TODO: Use MemoryExtensions.Count in .NET 8
+ while (segmentCount <= JwtConstants.MaxJwtSegmentCount && ((pos = token.IndexOf('.', pos)) >= 0))
+ {
+ pos++;
+ segmentCount++;
+ }
+
+ switch (segmentCount)
+ {
+ case JwtConstants.JwsSegmentCount:
+ return JwtTokenUtilities.RegexJws.IsMatch(token);
+
+ case JwtConstants.JweSegmentCount:
+ return JwtTokenUtilities.RegexJwe.IsMatch(token);
+
+ default:
+ LogHelper.LogInformation(LogMessages.IDX14107);
+ return false;
+ }
}
///
@@ -1440,7 +1450,7 @@ private static TokenValidationResult ReadToken(string token, TokenValidationPara
/// The JWT token
/// The to be used for validation.
///
- private async Task ValidateTokenAsync(JsonWebToken jsonWebToken, TokenValidationParameters validationParameters)
+ private async ValueTask ValidateTokenAsync(JsonWebToken jsonWebToken, TokenValidationParameters validationParameters)
{
BaseConfiguration currentConfiguration = null;
if (validationParameters.ConfigurationManager != null)
@@ -1519,15 +1529,14 @@ private async Task ValidateTokenAsync(JsonWebToken jsonWe
return tokenValidationResult;
}
- private async Task ValidateTokenAsync(JsonWebToken jsonWebToken, TokenValidationParameters validationParameters, BaseConfiguration configuration)
+ private ValueTask ValidateTokenAsync(JsonWebToken jsonWebToken, TokenValidationParameters validationParameters, BaseConfiguration configuration)
{
- if (jsonWebToken.IsEncrypted)
- return await ValidateJWEAsync(jsonWebToken, validationParameters, configuration).ConfigureAwait(false);
-
- return await ValidateJWSAsync(jsonWebToken, validationParameters, configuration).ConfigureAwait(false);
+ return jsonWebToken.IsEncrypted ?
+ ValidateJWEAsync(jsonWebToken, validationParameters, configuration) :
+ ValidateJWSAsync(jsonWebToken, validationParameters, configuration);
}
- private async Task ValidateJWSAsync(JsonWebToken jsonWebToken, TokenValidationParameters validationParameters, BaseConfiguration configuration)
+ private async ValueTask ValidateJWSAsync(JsonWebToken jsonWebToken, TokenValidationParameters validationParameters, BaseConfiguration configuration)
{
try
{
@@ -1571,7 +1580,7 @@ private async Task ValidateJWSAsync(JsonWebToken jsonWebT
}
}
- private async Task ValidateJWEAsync(JsonWebToken jwtToken, TokenValidationParameters validationParameters, BaseConfiguration configuration)
+ private async ValueTask ValidateJWEAsync(JsonWebToken jwtToken, TokenValidationParameters validationParameters, BaseConfiguration configuration)
{
try
{
@@ -1642,7 +1651,7 @@ private static JsonWebToken ValidateSignatureAndIssuerSecurityKey(JsonWebToken j
return validatedToken;
}
- private async Task ValidateTokenPayloadAsync(JsonWebToken jsonWebToken, TokenValidationParameters validationParameters, BaseConfiguration configuration)
+ private async ValueTask ValidateTokenPayloadAsync(JsonWebToken jsonWebToken, TokenValidationParameters validationParameters, BaseConfiguration configuration)
{
var expires = jsonWebToken.HasPayloadClaim(JwtRegisteredClaimNames.Exp) ? (DateTime?)jsonWebToken.ValidTo : null;
var notBefore = jsonWebToken.HasPayloadClaim(JwtRegisteredClaimNames.Nbf) ? (DateTime?)jsonWebToken.ValidFrom : null;
@@ -1715,7 +1724,7 @@ private static JsonWebToken ValidateSignature(JsonWebToken jwtToken, TokenValida
// 1. User specified delegate: IssuerSigningKeyResolver returned null
// 2. ResolveIssuerSigningKey returned null
// Try all the keys. This is the degenerate case, not concerned about perf.
- keys = TokenUtilities.GetAllSigningKeys(validationParameters, configuration);
+ keys = TokenUtilities.GetAllSigningKeys(configuration, validationParameters);
}
// keep track of exceptions thrown, keys that were tried
@@ -1751,7 +1760,7 @@ private static JsonWebToken ValidateSignature(JsonWebToken jwtToken, TokenValida
}
// Get information on where keys used during token validation came from for debugging purposes.
- var keysInTokenValidationParameters = TokenUtilities.GetAllSigningKeys(validationParameters);
+ var keysInTokenValidationParameters = TokenUtilities.GetAllSigningKeys(validationParameters: validationParameters);
var keysInConfiguration = TokenUtilities.GetAllSigningKeys(configuration);
var numKeysInTokenValidationParameters = keysInTokenValidationParameters.Count();
var numKeysInConfiguration = keysInConfiguration.Count();
@@ -1760,7 +1769,8 @@ private static JsonWebToken ValidateSignature(JsonWebToken jwtToken, TokenValida
{
if (kidMatched)
{
- var isKidInTVP = keysInTokenValidationParameters.Any(x => x.KeyId.Equals(jwtToken.Kid));
+ JsonWebToken localJwtToken = jwtToken; // avoid closure on non-exceptional path
+ var isKidInTVP = keysInTokenValidationParameters.Any(x => x.KeyId.Equals(localJwtToken.Kid));
var keyLocation = isKidInTVP ? "TokenValidationParameters" : "Configuration";
throw LogHelper.LogExceptionMessage(new SecurityTokenInvalidSignatureException(LogHelper.FormatInvariant(TokenLogMessages.IDX10511,
keysAttempted,
diff --git a/src/Microsoft.IdentityModel.JsonWebTokens/JwtTokenUtilities.cs b/src/Microsoft.IdentityModel.JsonWebTokens/JwtTokenUtilities.cs
index 4dbbe5e9ff..0823fc1b95 100644
--- a/src/Microsoft.IdentityModel.JsonWebTokens/JwtTokenUtilities.cs
+++ b/src/Microsoft.IdentityModel.JsonWebTokens/JwtTokenUtilities.cs
@@ -10,9 +10,9 @@
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
-using Microsoft.IdentityModel.Json.Linq;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
+using Newtonsoft.Json.Linq;
using TokenLogMessages = Microsoft.IdentityModel.Tokens.LogMessages;
namespace Microsoft.IdentityModel.JsonWebTokens
@@ -498,33 +498,6 @@ internal static SecurityKey ResolveTokenSigningKey(string kid, string x5t, IEnum
return null;
}
- ///
- /// Counts the number of Jwt Token segments.
- ///
- /// The Jwt Token.
- /// The maximum number of segments to count up to.
- /// The number of segments up to .
- internal static int CountJwtTokenPart(string token, int maxCount)
- {
- var count = 1;
- var index = 0;
- while (index < token.Length)
- {
- var dotIndex = token.IndexOf('.', index);
- if (dotIndex < 0)
- {
- break;
- }
- count++;
- index = dotIndex + 1;
- if (count == maxCount)
- {
- break;
- }
- }
- return count;
- }
-
internal static IEnumerable ConcatSigningKeys(TokenValidationParameters tvp)
{
if (tvp == null)
diff --git a/src/Microsoft.IdentityModel.KeyVaultExtensions/Microsoft.IdentityModel.KeyVaultExtensions.csproj b/src/Microsoft.IdentityModel.KeyVaultExtensions/Microsoft.IdentityModel.KeyVaultExtensions.csproj
index da42273460..7a2295cb2d 100644
--- a/src/Microsoft.IdentityModel.KeyVaultExtensions/Microsoft.IdentityModel.KeyVaultExtensions.csproj
+++ b/src/Microsoft.IdentityModel.KeyVaultExtensions/Microsoft.IdentityModel.KeyVaultExtensions.csproj
@@ -24,7 +24,6 @@
all
runtime; build; native; contentfiles; analyzers; buildtransitive
-
diff --git a/src/Microsoft.IdentityModel.Logging/LogHelper.cs b/src/Microsoft.IdentityModel.Logging/LogHelper.cs
index 467cd3606e..495da634cb 100644
--- a/src/Microsoft.IdentityModel.Logging/LogHelper.cs
+++ b/src/Microsoft.IdentityModel.Logging/LogHelper.cs
@@ -2,12 +2,10 @@
// Licensed under the MIT License.
using System;
-using System.Data;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Tracing;
using System.Globalization;
using System.Linq;
-using System.Text.RegularExpressions;
using Microsoft.IdentityModel.Abstractions;
namespace Microsoft.IdentityModel.Logging
@@ -260,9 +258,9 @@ public static Exception LogExceptionMessage(EventLevel eventLevel, Exception exc
if (IdentityModelEventSource.Logger.IsEnabled() && IdentityModelEventSource.Logger.LogLevel >= eventLevel)
IdentityModelEventSource.Logger.Write(eventLevel, exception.InnerException, exception.Message);
- EventLogLevel eventLogLevel = Enum.IsDefined(typeof(EventLogLevel), (int)eventLevel) ? (EventLogLevel)eventLevel : EventLogLevel.Error;
+ EventLogLevel eventLogLevel = EventLevelToEventLogLevel(eventLevel);
if (Logger.IsEnabled(eventLogLevel))
- Logger.Log(WriteEntry((EventLogLevel)eventLevel, exception.InnerException, exception.Message, null));
+ Logger.Log(WriteEntry(eventLogLevel, exception.InnerException, exception.Message, null));
return exception;
}
@@ -277,8 +275,8 @@ public static void LogInformation(string message, params object[] args)
if (IdentityModelEventSource.Logger.IsEnabled() && IdentityModelEventSource.Logger.LogLevel >= EventLevel.Informational)
IdentityModelEventSource.Logger.WriteInformation(message, args);
- if (Enum.IsDefined(typeof(EventLogLevel), (int)EventLevel.Informational) && Logger.IsEnabled((EventLogLevel)EventLevel.Informational))
- Logger.Log(WriteEntry((EventLogLevel)EventLevel.Informational, null, message, args));
+ if (Logger.IsEnabled(EventLogLevel.Informational))
+ Logger.Log(WriteEntry(EventLogLevel.Informational, null, message, args));
}
///
@@ -291,8 +289,8 @@ public static void LogVerbose(string message, params object[] args)
if (IdentityModelEventSource.Logger.IsEnabled())
IdentityModelEventSource.Logger.WriteVerbose(message, args);
- if (Enum.IsDefined(typeof(EventLogLevel), (int)EventLevel.Verbose) && Logger.IsEnabled((EventLogLevel)EventLevel.Verbose))
- Logger.Log(WriteEntry((EventLogLevel)EventLevel.Verbose, null, message, args));
+ if (Logger.IsEnabled(EventLogLevel.Verbose))
+ Logger.Log(WriteEntry(EventLogLevel.Verbose, null, message, args));
}
///
@@ -305,8 +303,8 @@ public static void LogWarning(string message, params object[] args)
if (IdentityModelEventSource.Logger.IsEnabled())
IdentityModelEventSource.Logger.WriteWarning(message, args);
- if (Enum.IsDefined(typeof(EventLogLevel), (int)EventLevel.Warning) && Logger.IsEnabled((EventLogLevel)EventLevel.Warning))
- Logger.Log(WriteEntry((EventLogLevel)EventLevel.Warning, null, message, args));
+ if (Logger.IsEnabled(EventLogLevel.Warning))
+ Logger.Log(WriteEntry(EventLogLevel.Warning, null, message, args));
}
///
@@ -319,8 +317,7 @@ public static void LogWarning(string message, params object[] args)
/// An object array that contains zero or more objects to format.
private static T LogExceptionImpl<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(EventLevel eventLevel, string argumentName, Exception innerException, string format, params object[] args) where T : Exception
{
- string message = null;
-
+ string message;
if (args != null)
message = string.Format(CultureInfo.InvariantCulture, format, args);
else
@@ -329,9 +326,9 @@ public static void LogWarning(string message, params object[] args)
if (IdentityModelEventSource.Logger.IsEnabled() && IdentityModelEventSource.Logger.LogLevel >= eventLevel)
IdentityModelEventSource.Logger.Write(eventLevel, innerException, message);
- EventLogLevel eventLogLevel = Enum.IsDefined(typeof(EventLogLevel), (int)eventLevel) ? (EventLogLevel)eventLevel : EventLogLevel.Error;
+ EventLogLevel eventLogLevel = EventLevelToEventLogLevel(eventLevel);
if (Logger.IsEnabled(eventLogLevel))
- Logger.Log(WriteEntry((EventLogLevel)eventLevel, innerException, message, null));
+ Logger.Log(WriteEntry(eventLogLevel, innerException, message, null));
if (innerException != null)
if (string.IsNullOrEmpty(argumentName))
@@ -345,6 +342,9 @@ public static void LogWarning(string message, params object[] args)
return (T)Activator.CreateInstance(typeof(T), argumentName, message);
}
+ private static EventLogLevel EventLevelToEventLogLevel(EventLevel eventLevel) =>
+ (uint)(int)eventLevel <= 5 ? (EventLogLevel)eventLevel : EventLogLevel.Error;
+
///
/// Formats the string using InvariantCulture
///
diff --git a/src/Microsoft.IdentityModel.ManagedKeyVaultSecurityKey/Microsoft.IdentityModel.ManagedKeyVaultSecurityKey.csproj b/src/Microsoft.IdentityModel.ManagedKeyVaultSecurityKey/Microsoft.IdentityModel.ManagedKeyVaultSecurityKey.csproj
index b7ce451880..7f1caaa2a4 100644
--- a/src/Microsoft.IdentityModel.ManagedKeyVaultSecurityKey/Microsoft.IdentityModel.ManagedKeyVaultSecurityKey.csproj
+++ b/src/Microsoft.IdentityModel.ManagedKeyVaultSecurityKey/Microsoft.IdentityModel.ManagedKeyVaultSecurityKey.csproj
@@ -25,7 +25,6 @@
all
runtime; build; native; contentfiles; analyzers; buildtransitive
-
diff --git a/src/Microsoft.IdentityModel.Protocols.OpenIdConnect/Configuration/OpenIdConnectConfiguration.cs b/src/Microsoft.IdentityModel.Protocols.OpenIdConnect/Configuration/OpenIdConnectConfiguration.cs
index 77252a50fc..96c4f5d4dc 100644
--- a/src/Microsoft.IdentityModel.Protocols.OpenIdConnect/Configuration/OpenIdConnectConfiguration.cs
+++ b/src/Microsoft.IdentityModel.Protocols.OpenIdConnect/Configuration/OpenIdConnectConfiguration.cs
@@ -5,9 +5,9 @@
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
-using Microsoft.IdentityModel.Json;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
+using Newtonsoft.Json;
namespace Microsoft.IdentityModel.Protocols.OpenIdConnect
{
diff --git a/src/Microsoft.IdentityModel.Protocols.OpenIdConnect/Configuration/OpenIdConnectConfigurationRetriever.cs b/src/Microsoft.IdentityModel.Protocols.OpenIdConnect/Configuration/OpenIdConnectConfigurationRetriever.cs
index 10704df74e..597dd47cb9 100644
--- a/src/Microsoft.IdentityModel.Protocols.OpenIdConnect/Configuration/OpenIdConnectConfigurationRetriever.cs
+++ b/src/Microsoft.IdentityModel.Protocols.OpenIdConnect/Configuration/OpenIdConnectConfigurationRetriever.cs
@@ -4,9 +4,9 @@
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
-using Microsoft.IdentityModel.Json;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
+using Newtonsoft.Json;
namespace Microsoft.IdentityModel.Protocols.OpenIdConnect
{
diff --git a/src/Microsoft.IdentityModel.Protocols.OpenIdConnect/OpenIdConnectMessage.cs b/src/Microsoft.IdentityModel.Protocols.OpenIdConnect/OpenIdConnectMessage.cs
index fc5ce4f4df..6f4e45c955 100644
--- a/src/Microsoft.IdentityModel.Protocols.OpenIdConnect/OpenIdConnectMessage.cs
+++ b/src/Microsoft.IdentityModel.Protocols.OpenIdConnect/OpenIdConnectMessage.cs
@@ -5,8 +5,8 @@
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
-using Microsoft.IdentityModel.Json.Linq;
using Microsoft.IdentityModel.Logging;
+using Newtonsoft.Json.Linq;
namespace Microsoft.IdentityModel.Protocols.OpenIdConnect
{
diff --git a/src/Microsoft.IdentityModel.Protocols.SignedHttpRequest/GlobalSuppressions.cs b/src/Microsoft.IdentityModel.Protocols.SignedHttpRequest/GlobalSuppressions.cs
index f20f3e4fd0..03d3894c07 100644
--- a/src/Microsoft.IdentityModel.Protocols.SignedHttpRequest/GlobalSuppressions.cs
+++ b/src/Microsoft.IdentityModel.Protocols.SignedHttpRequest/GlobalSuppressions.cs
@@ -12,4 +12,3 @@
[assembly: SuppressMessage("Globalization", "CA1307:Specify StringComparison", Justification = "Vendored component", Scope = "module")]
[assembly: SuppressMessage("Design", "CA1001:Types that own disposable fields should be disposable", Justification = "Breaking change", Scope = "type", Target = "~T:Microsoft.IdentityModel.Protocols.SignedHttpRequest.SignedHttpRequestHandler")]
[assembly: SuppressMessage("Usage", "CA2227:Collection properties should be read only", Justification = "Previously released as read / write", Scope = "member", Target = "~P:Microsoft.IdentityModel.Protocols.SignedHttpRequest.SignedHttpRequestInvalidNonceClaimException.PropertyBag")]
-[assembly: SuppressMessage("Globalization", "CA1305:Specify IFormatProvider", Justification = "Breaking Change", Scope = "member", Target = "~T:Microsoft.IdentityModel.Protocols.SignedHttpRequest.SignedHttpRequestHandler)")]
diff --git a/src/Microsoft.IdentityModel.Protocols.SignedHttpRequest/SignedHttpRequestHandler.cs b/src/Microsoft.IdentityModel.Protocols.SignedHttpRequest/SignedHttpRequestHandler.cs
index 5f5a4962ff..0ec1bae3a4 100644
--- a/src/Microsoft.IdentityModel.Protocols.SignedHttpRequest/SignedHttpRequestHandler.cs
+++ b/src/Microsoft.IdentityModel.Protocols.SignedHttpRequest/SignedHttpRequestHandler.cs
@@ -32,11 +32,11 @@
using System.Text;
using System.Threading;
using System.Threading.Tasks;
-using Microsoft.IdentityModel.Json;
-using Microsoft.IdentityModel.Json.Linq;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
+using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
namespace Microsoft.IdentityModel.Protocols.SignedHttpRequest
{
@@ -1213,11 +1213,18 @@ private static string CalculateBase64UrlEncodedHash(string data)
private static string CalculateBase64UrlEncodedHash(byte[] bytes)
{
+ byte[] hashedBytes;
+
+#if NET6_0_OR_GREATER
+ hashedBytes = SHA256.HashData(bytes);
+#else
using (var hash = SHA256.Create())
{
- var hashedBytes = hash.ComputeHash(bytes);
- return Base64UrlEncoder.Encode(hashedBytes);
+ hashedBytes = hash.ComputeHash(bytes);
}
+#endif
+
+ return Base64UrlEncoder.Encode(hashedBytes);
}
///
diff --git a/src/Microsoft.IdentityModel.Protocols.WsFederation/Configuration/WsFederationConfiguration.cs b/src/Microsoft.IdentityModel.Protocols.WsFederation/Configuration/WsFederationConfiguration.cs
index 87a98ae157..e28debd71a 100644
--- a/src/Microsoft.IdentityModel.Protocols.WsFederation/Configuration/WsFederationConfiguration.cs
+++ b/src/Microsoft.IdentityModel.Protocols.WsFederation/Configuration/WsFederationConfiguration.cs
@@ -22,7 +22,7 @@ public WsFederationConfiguration()
///
/// The element that was found when reading metadata.
///
- public Signature? Signature
+ public Signature Signature
{
get;
set;
@@ -31,7 +31,7 @@ public Signature? Signature
///
/// The that was used to sign the metadata.
///
- public SigningCredentials? SigningCredentials
+ public SigningCredentials SigningCredentials
{
get;
set;
diff --git a/src/Microsoft.IdentityModel.Protocols.WsFederation/Configuration/WsFederationConfigurationValidator.cs b/src/Microsoft.IdentityModel.Protocols.WsFederation/Configuration/WsFederationConfigurationValidator.cs
index 9dcb8fbcd9..d5d5275e02 100644
--- a/src/Microsoft.IdentityModel.Protocols.WsFederation/Configuration/WsFederationConfigurationValidator.cs
+++ b/src/Microsoft.IdentityModel.Protocols.WsFederation/Configuration/WsFederationConfigurationValidator.cs
@@ -143,7 +143,7 @@ public ConfigurationValidationResult Validate(WsFederationConfiguration configur
var signatureCertData = signatureX509Data.Current.Certificates.GetEnumerator();
if (signatureCertData.MoveNext() && !string.IsNullOrWhiteSpace(signatureCertData.Current))
{
- X509Certificate2? cert = null;
+ X509Certificate2 cert = null;
try
{
diff --git a/src/Microsoft.IdentityModel.Protocols.WsFederation/Microsoft.IdentityModel.Protocols.WsFederation.csproj b/src/Microsoft.IdentityModel.Protocols.WsFederation/Microsoft.IdentityModel.Protocols.WsFederation.csproj
index 0e283fce97..7550ca2c13 100644
--- a/src/Microsoft.IdentityModel.Protocols.WsFederation/Microsoft.IdentityModel.Protocols.WsFederation.csproj
+++ b/src/Microsoft.IdentityModel.Protocols.WsFederation/Microsoft.IdentityModel.Protocols.WsFederation.csproj
@@ -8,7 +8,6 @@
true
Microsoft.IdentityModel.Protocols.WsFederation
.NET;Windows;Authentication;Identity;WsFederation
- enable
diff --git a/src/Microsoft.IdentityModel.Protocols.WsFederation/QueryHelper.cs b/src/Microsoft.IdentityModel.Protocols.WsFederation/QueryHelper.cs
index 0ddca7d3bd..0a97f8dc08 100644
--- a/src/Microsoft.IdentityModel.Protocols.WsFederation/QueryHelper.cs
+++ b/src/Microsoft.IdentityModel.Protocols.WsFederation/QueryHelper.cs
@@ -34,7 +34,7 @@ public static IDictionary> ParseQuery(string queryString)
///
/// The raw query string value, with or without the leading '?'.
/// A collection of parsed keys and values, null if there are no entries.
- public static IDictionary>? ParseNullableQuery(string queryString)
+ public static IDictionary> ParseNullableQuery(string queryString)
{
var accumulator = new KeyValueAccumulator();
diff --git a/src/Microsoft.IdentityModel.Protocols.WsFederation/SecurityTokenServiceTypeRoleDescriptor.cs b/src/Microsoft.IdentityModel.Protocols.WsFederation/SecurityTokenServiceTypeRoleDescriptor.cs
index 3bc5fbd8d0..2bddf7dd21 100644
--- a/src/Microsoft.IdentityModel.Protocols.WsFederation/SecurityTokenServiceTypeRoleDescriptor.cs
+++ b/src/Microsoft.IdentityModel.Protocols.WsFederation/SecurityTokenServiceTypeRoleDescriptor.cs
@@ -24,17 +24,7 @@ public List KeyInfos
/// Passive Requestor Token endpoint
/// fed:PassiveRequestorEndpoint, https://docs.oasis-open.org/wsfed/federation/v1.2/os/ws-federation-1.2-spec-os.html#:~:text=fed%3ASecurityTokenServiceType/fed%3APassiveRequestorEndpoint
///
- public string? TokenEndpoint
- {
- get;
- set;
- }
-
- ///
- /// Active Requestor Token Endpoint
- /// fed:SecurityTokenServiceType, http://docs.oasis-open.org/wsfed/federation/v1.2/os/ws-federation-1.2-spec-os.html#:~:text=fed%3ASecurityTokenSerivceEndpoint
- ///
- public string? ActiveTokenEndpoint
+ public string TokenEndpoint
{
get;
set;
diff --git a/src/Microsoft.IdentityModel.Protocols.WsFederation/WsFederationMessage.cs b/src/Microsoft.IdentityModel.Protocols.WsFederation/WsFederationMessage.cs
index 8be214b9ef..9b7709954a 100644
--- a/src/Microsoft.IdentityModel.Protocols.WsFederation/WsFederationMessage.cs
+++ b/src/Microsoft.IdentityModel.Protocols.WsFederation/WsFederationMessage.cs
@@ -137,7 +137,7 @@ public string CreateSignOutUrl()
///
/// the 'SecurityToken'.
/// if exception occurs while reading security token.
- public virtual string? GetToken()
+ public virtual string GetToken()
{
return GetTokenUsingXmlReader();
}
@@ -149,7 +149,7 @@ public string CreateSignOutUrl()
/// This is only called after it is determined the Wresult is well formed xml. A successful call the GetTokenUsingXmlReader should be made first.
///
/// the string version of the security token.
- internal static string? GetToken(string wresult)
+ internal static string GetToken(string wresult)
{
if (string.IsNullOrEmpty(wresult))
{
@@ -217,7 +217,7 @@ public string CreateSignOutUrl()
///
/// the 'SecurityToken'.
/// if exception occurs while reading security token.
- public virtual string? GetTokenUsingXmlReader()
+ public virtual string GetTokenUsingXmlReader()
{
if (Wresult == null)
{
@@ -225,7 +225,7 @@ public string CreateSignOutUrl()
return null;
}
- string? token = null;
+ string token = null;
using (var sr = new StringReader(Wresult))
using (var xmlReader = new XmlTextReader(sr) { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null })
{
diff --git a/src/Microsoft.IdentityModel.Protocols.WsFederation/WsFederationMetadataSerializer.cs b/src/Microsoft.IdentityModel.Protocols.WsFederation/WsFederationMetadataSerializer.cs
index 33df92e5cc..5bc0929711 100644
--- a/src/Microsoft.IdentityModel.Protocols.WsFederation/WsFederationMetadataSerializer.cs
+++ b/src/Microsoft.IdentityModel.Protocols.WsFederation/WsFederationMetadataSerializer.cs
@@ -264,7 +264,7 @@ protected virtual string ReadPassiveRequestorEndpoint(XmlReader reader)
/// used to read SecurityTokenServiceEndpoint.
/// Active token endpoint string
/// If an error occurs while reading the SecurityTokenServiceEndpoint
- protected virtual string? ReadSecurityTokenServiceEndpoint(XmlReader reader)
+ protected virtual string ReadSecurityTokenServiceEndpoint(XmlReader reader)
{
XmlUtil.CheckReaderOnEntry(reader, Elements.SecurityTokenServiceEndpoint, Namespace);
@@ -286,7 +286,7 @@ protected virtual string ReadPassiveRequestorEndpoint(XmlReader reader)
if (reader.IsEmptyElement)
throw XmlUtil.LogReadException(LogMessages.IDX22814);
- string? tokenEndpoint = null;
+ string tokenEndpoint = null;
while (reader.IsStartElement())
{
diff --git a/src/Microsoft.IdentityModel.TestExtensions/TestTokenCreator.cs b/src/Microsoft.IdentityModel.TestExtensions/TestTokenCreator.cs
index 5e960cf8c8..077796188e 100644
--- a/src/Microsoft.IdentityModel.TestExtensions/TestTokenCreator.cs
+++ b/src/Microsoft.IdentityModel.TestExtensions/TestTokenCreator.cs
@@ -5,10 +5,10 @@
using System.Collections.Generic;
using System.Security.Claims;
using System.Security.Cryptography;
-using Microsoft.IdentityModel.Json;
-using Microsoft.IdentityModel.Json.Linq;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
+using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
namespace Microsoft.IdentityModel.TestExtensions
{
@@ -421,7 +421,7 @@ public static string CreateJsonPayload(IDictionary claims)
if (claims == null)
throw new ArgumentNullException(nameof(claims));
- var jobj = new Microsoft.IdentityModel.Json.Linq.JObject();
+ var jobj = new JObject();
foreach (var claim in claims)
jobj.Add(claim.Key, JToken.FromObject(claim.Value));
diff --git a/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.cs b/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.cs
index 874ecf1722..5759413506 100644
--- a/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.cs
+++ b/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.cs
@@ -1042,7 +1042,7 @@ private SamlSecurityToken ValidateSignature(SamlSecurityToken samlToken, string
// 1. User specified delegate: IssuerSigningKeyResolver returned null
// 2. ResolveIssuerSigningKey returned null
// Try all the keys. This is the degenerate case, not concerned about perf.
- keys = TokenUtilities.GetAllSigningKeys(validationParameters);
+ keys = TokenUtilities.GetAllSigningKeys(validationParameters: validationParameters);
}
// keep track of exceptions thrown, keys that were tried
diff --git a/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlTokenUtilities.cs b/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlTokenUtilities.cs
index 16b55be7ba..2677b3663e 100644
--- a/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlTokenUtilities.cs
+++ b/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlTokenUtilities.cs
@@ -75,7 +75,7 @@ internal static IEnumerable GetKeysForTokenSignatureValidation(stri
keyMatched = false;
if (validationParameters.TryAllIssuerSigningKeys)
{
- return TokenUtilities.GetAllSigningKeys(validationParameters);
+ return TokenUtilities.GetAllSigningKeys(validationParameters: validationParameters);
}
}
}
diff --git a/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.cs b/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.cs
index 30c37eea29..6f17203279 100644
--- a/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.cs
+++ b/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.cs
@@ -423,7 +423,7 @@ private Saml2SecurityToken ValidateSignature(Saml2SecurityToken samlToken, strin
// 1. User specified delegate: IssuerSigningKeyResolver returned null
// 2. ResolveIssuerSigningKey returned null
// Try all the keys. This is the degenerate case, not concerned about perf.
- keys = TokenUtilities.GetAllSigningKeys(validationParameters);
+ keys = TokenUtilities.GetAllSigningKeys(validationParameters: validationParameters);
}
// keep track of exceptions thrown, keys that were tried
diff --git a/src/Microsoft.IdentityModel.Tokens/BaseConfiguration.cs b/src/Microsoft.IdentityModel.Tokens/BaseConfiguration.cs
index 85f1a7578c..a7e17f59f8 100644
--- a/src/Microsoft.IdentityModel.Tokens/BaseConfiguration.cs
+++ b/src/Microsoft.IdentityModel.Tokens/BaseConfiguration.cs
@@ -3,7 +3,7 @@
using System.Collections.Generic;
using System.Collections.ObjectModel;
-using Microsoft.IdentityModel.Json;
+using Newtonsoft.Json;
namespace Microsoft.IdentityModel.Tokens
{
diff --git a/src/Microsoft.IdentityModel.Tokens/GlobalSuppressions.cs b/src/Microsoft.IdentityModel.Tokens/GlobalSuppressions.cs
index adada5930c..fb7f339713 100644
--- a/src/Microsoft.IdentityModel.Tokens/GlobalSuppressions.cs
+++ b/src/Microsoft.IdentityModel.Tokens/GlobalSuppressions.cs
@@ -4,30 +4,13 @@
// a specific target and scoped to a namespace, type, member, etc.
using System.Diagnostics.CodeAnalysis;
-
-[assembly: SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "Vendored component", Scope = "namespaceanddescendants", Target = "Microsoft.IdentityModel.Json")]
-[assembly: SuppressMessage("Usage", "CA2213:Disposable fields should be disposed", Justification = "Vendored component", Scope = "namespaceanddescendants", Target = "Microsoft.IdentityModel.Json")]
-[assembly: SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "Vendored component", Scope = "namespaceanddescendants", Target = "Microsoft.IdentityModel.Json")]
-[assembly: SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Vendored component", Scope = "namespaceanddescendants", Target = "Microsoft.IdentityModel.Json")]
-[assembly: SuppressMessage("Design", "CA1064:Exceptions should be public", Justification = "Vendored component", Scope = "namespaceanddescendants", Target = "Microsoft.IdentityModel.Json")]
-[assembly: SuppressMessage("Performance", "CA1802:Use literals where appropriate", Justification = "Vendored component", Scope = "namespaceanddescendants", Target = "Microsoft.IdentityModel.Json")]
-[assembly: SuppressMessage("Usage", "CA2208:Instantiate argument exceptions correctly", Justification = "Vendored component", Scope = "namespaceanddescendants", Target = "Microsoft.IdentityModel.Json")]
-[assembly: SuppressMessage("Usage", "CA1801:Review unused parameters", Justification = "Vendored component", Scope = "namespaceanddescendants", Target = "Microsoft.IdentityModel.Json")]
-[assembly: SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "Vendored component", Scope = "namespaceanddescendants", Target = "Microsoft.IdentityModel.Json")]
-[assembly: SuppressMessage("Usage", "CA2207:Initialize value type static fields inline", Justification = "Vendored component", Scope = "namespaceanddescendants", Target = "Microsoft.IdentityModel.Json")]
-[assembly: SuppressMessage("Performance", "CA1810:Initialize reference type static fields inline", Justification = "Vendored component", Scope = "namespaceanddescendants", Target = "Microsoft.IdentityModel.Json")]
-[assembly: SuppressMessage("Performance", "CA1825:Avoid zero-length array allocations.", Justification = "vendored", Scope = "namespaceanddescendants", Target = "Microsoft.IdentityModel.Json")]
[assembly: SuppressMessage("Globalization", "CA1307:Specify StringComparison", Justification = "Vendored component", Scope = "module")]
-[assembly: SuppressMessage("Performance", "CA1820:Test for empty strings using string length", Justification = "Vendored component", Scope = "namespaceanddescendants", Target = "Microsoft.IdentityModel.Json")]
-[assembly: SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Vendored component", Scope = "namespaceanddescendants", Target = "Microsoft.IdentityModel.Json")]
-
[assembly: SuppressMessage("Usage", "CA2227:Collection properties should be read only", Justification = "Breaking change", Scope = "member", Target = "~P:Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor.AdditionalHeaderClaims")]
[assembly: SuppressMessage("Usage", "CA2227:Collection properties should be read only", Justification = "Breaking change", Scope = "member", Target = "~P:Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor.Claims")]
[assembly: SuppressMessage("Usage", "CA2227:Collection properties should be read only", Justification = "Breaking change", Scope = "member", Target = "~P:Microsoft.IdentityModel.Tokens.JsonWebKey.Oth")]
[assembly: SuppressMessage("Usage", "CA2227:Collection properties should be read only", Justification = "Breaking chnage", Scope = "member", Target = "~P:Microsoft.IdentityModel.Tokens.TokenValidationParameters.PropertyBag")]
[assembly: SuppressMessage("Usage", "CA2214:Do not call overridable methods in constructors", Justification = "Current design", Scope = "member", Target = "~M:Microsoft.IdentityModel.Tokens.TokenValidationParameters.#ctor(Microsoft.IdentityModel.Tokens.TokenValidationParameters)")]
[assembly: SuppressMessage("Usage", "CA2213:Disposable fields should be disposed", Justification = "Disposed through ReleaseSignatureProvider", Scope = "member", Target = "~F:Microsoft.IdentityModel.Tokens.AuthenticatedEncryptionProvider._symmetricSignatureProvider")]
-[assembly: SuppressMessage("Reliability", "CA2002:Do not lock on objects with weak identity", Justification = "Listener doesn't have a sync lock", Scope = "member", Target = "~M:Microsoft.IdentityModel.Json.Serialization.DiagnosticsTraceWriter.Trace(System.Diagnostics.TraceLevel,System.String,System.Exception)")]
[assembly: SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "Ownership is transfered", Scope = "member", Target = "~M:Microsoft.IdentityModel.Tokens.AsymmetricAdapter.InitializeUsingRsaSecurityKey(Microsoft.IdentityModel.Tokens.RsaSecurityKey,System.String)")]
[assembly: SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "Ownership is transfered", Scope = "member", Target = "~M:Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateSignatureProvider(Microsoft.IdentityModel.Tokens.SecurityKey,System.String,System.Boolean,System.Boolean)~Microsoft.IdentityModel.Tokens.SignatureProvider")]
[assembly: SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "Doesn't own object", Scope = "member", Target = "~M:Microsoft.IdentityModel.Tokens.InMemoryCryptoProviderCache.TryRemove(Microsoft.IdentityModel.Tokens.SignatureProvider)~System.Boolean")]
diff --git a/src/Microsoft.IdentityModel.Tokens/JsonWebKey.cs b/src/Microsoft.IdentityModel.Tokens/JsonWebKey.cs
index c00ef45cd8..6f0204d2e4 100644
--- a/src/Microsoft.IdentityModel.Tokens/JsonWebKey.cs
+++ b/src/Microsoft.IdentityModel.Tokens/JsonWebKey.cs
@@ -4,9 +4,9 @@
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
-using Microsoft.IdentityModel.Json;
-using Microsoft.IdentityModel.Json.Linq;
using Microsoft.IdentityModel.Logging;
+using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
namespace Microsoft.IdentityModel.Tokens
{
diff --git a/src/Microsoft.IdentityModel.Tokens/JsonWebKeySet.cs b/src/Microsoft.IdentityModel.Tokens/JsonWebKeySet.cs
index a9e4a7cc2d..2b270c22ff 100644
--- a/src/Microsoft.IdentityModel.Tokens/JsonWebKeySet.cs
+++ b/src/Microsoft.IdentityModel.Tokens/JsonWebKeySet.cs
@@ -5,7 +5,7 @@
using System.Collections.Generic;
using System.ComponentModel;
using Microsoft.IdentityModel.Logging;
-using Microsoft.IdentityModel.Json;
+using Newtonsoft.Json;
namespace Microsoft.IdentityModel.Tokens
{
diff --git a/src/Microsoft.IdentityModel.Tokens/Microsoft.IdentityModel.Tokens.csproj b/src/Microsoft.IdentityModel.Tokens/Microsoft.IdentityModel.Tokens.csproj
index 22a02c7846..ef494717db 100644
--- a/src/Microsoft.IdentityModel.Tokens/Microsoft.IdentityModel.Tokens.csproj
+++ b/src/Microsoft.IdentityModel.Tokens/Microsoft.IdentityModel.Tokens.csproj
@@ -43,6 +43,7 @@
+
diff --git a/src/Microsoft.IdentityModel.Tokens/SecurityKey.cs b/src/Microsoft.IdentityModel.Tokens/SecurityKey.cs
index ac5cdce62f..08f486f4db 100644
--- a/src/Microsoft.IdentityModel.Tokens/SecurityKey.cs
+++ b/src/Microsoft.IdentityModel.Tokens/SecurityKey.cs
@@ -3,7 +3,7 @@
using System;
using Microsoft.IdentityModel.Logging;
-using Microsoft.IdentityModel.Json;
+using Newtonsoft.Json;
namespace Microsoft.IdentityModel.Tokens
{
diff --git a/src/Microsoft.IdentityModel.Tokens/SymmetricSignatureProvider.cs b/src/Microsoft.IdentityModel.Tokens/SymmetricSignatureProvider.cs
index b7b98bcadb..6c70134f37 100644
--- a/src/Microsoft.IdentityModel.Tokens/SymmetricSignatureProvider.cs
+++ b/src/Microsoft.IdentityModel.Tokens/SymmetricSignatureProvider.cs
@@ -3,6 +3,8 @@
using System;
using System.Collections.Generic;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using Microsoft.IdentityModel.Logging;
@@ -289,6 +291,9 @@ public override bool Verify(byte[] input, int inputOffset, int inputLength, byte
/// how many bytes to verfiy.
/// algorithm passed by AuthenticatedEncryptionProvider.
/// true if computed signature matches the signature parameter, false otherwise.
+#if NET6_0_OR_GREATER
+ [SkipLocalsInit]
+#endif
internal bool Verify(byte[] input, int inputOffset, int inputLength, byte[] signature, int signatureOffset, int signatureLength, string algorithm)
{
if (input == null || input.Length == 0)
@@ -377,7 +382,17 @@ internal bool Verify(byte[] input, int inputOffset, int inputLength, byte[] sign
try
{
keyedHashAlgorithm = GetKeyedHashAlgorithm(GetKeyBytes(Key), Algorithm);
- return Utility.AreEqual(signature, keyedHashAlgorithm.ComputeHash(input, inputOffset, inputLength), signatureLength);
+
+ scoped Span hash;
+#if NET6_0_OR_GREATER
+ hash = stackalloc byte[keyedHashAlgorithm.HashSize / 8]; // only known algorithms are used, all of which have a small enough hash size to stackalloc
+ keyedHashAlgorithm.TryComputeHash(input.AsSpan(inputOffset, inputLength), hash, out int bytesWritten);
+ Debug.Assert(bytesWritten == hash.Length);
+#else
+ hash = keyedHashAlgorithm.ComputeHash(input, inputOffset, inputLength).AsSpan();
+#endif
+
+ return Utility.AreEqual(signature, hash, signatureLength);
}
catch
{
diff --git a/src/Microsoft.IdentityModel.Tokens/TokenUtilities.cs b/src/Microsoft.IdentityModel.Tokens/TokenUtilities.cs
index 6d202a24d4..6171c226e4 100644
--- a/src/Microsoft.IdentityModel.Tokens/TokenUtilities.cs
+++ b/src/Microsoft.IdentityModel.Tokens/TokenUtilities.cs
@@ -6,7 +6,7 @@
using System.Globalization;
using System.Linq;
using System.Security.Claims;
-using Microsoft.IdentityModel.Json.Linq;
+using Newtonsoft.Json.Linq;
using Microsoft.IdentityModel.Logging;
using TokenLogMessages = Microsoft.IdentityModel.Tokens.LogMessages;
@@ -112,47 +112,38 @@ internal static object GetClaimValueUsingValueType(Claim claim)
}
///
- /// Returns all provided in validationParameters.
+ /// Returns all provided in and .
///
+ /// The that contains signing keys used for validation.
/// A required for validation.
- /// Returns all provided in validationParameters.
- internal static IEnumerable GetAllSigningKeys(TokenValidationParameters validationParameters)
+ /// Returns all provided in provided in and .
+ internal static IEnumerable GetAllSigningKeys(BaseConfiguration configuration = null, TokenValidationParameters validationParameters = null)
{
- LogHelper.LogInformation(TokenLogMessages.IDX10243);
- if (validationParameters.IssuerSigningKey != null)
- yield return validationParameters.IssuerSigningKey;
-
- if (validationParameters.IssuerSigningKeys != null)
- foreach (SecurityKey key in validationParameters.IssuerSigningKeys)
- yield return key;
- }
+ if (configuration is not null)
+ {
+ if (validationParameters is not null)
+ {
+ LogHelper.LogInformation(TokenLogMessages.IDX10264);
+ }
+ LogHelper.LogInformation(TokenLogMessages.IDX10265);
- ///
- /// Returns all provided in .
- ///
- /// The that contains signing keys used for validation.
- /// Returns all provided in provided in .
- internal static IEnumerable GetAllSigningKeys(BaseConfiguration configuration)
- {
- LogHelper.LogInformation(TokenLogMessages.IDX10265);
+ if (configuration?.SigningKeys != null)
+ foreach (SecurityKey key in configuration.SigningKeys)
+ yield return key;
+ }
- if (configuration?.SigningKeys != null)
- foreach (SecurityKey key in configuration.SigningKeys)
- yield return key;
- }
+ if (validationParameters is not null)
+ {
+ LogHelper.LogInformation(TokenLogMessages.IDX10243);
- ///
- /// Returns all provided in and .
- ///
- /// The that contains signing keys used for validation.
- /// A required for validation.
- /// Returns all provided in provided in and .
- internal static IEnumerable GetAllSigningKeys(TokenValidationParameters validationParameters, BaseConfiguration configuration)
- {
- LogHelper.LogInformation(TokenLogMessages.IDX10264);
+ if (validationParameters.IssuerSigningKey != null)
+ yield return validationParameters.IssuerSigningKey;
- return GetAllSigningKeys(configuration).Concat(GetAllSigningKeys(validationParameters));
+ if (validationParameters.IssuerSigningKeys != null)
+ foreach (SecurityKey key in validationParameters.IssuerSigningKeys)
+ yield return key;
+ }
}
///
diff --git a/src/Microsoft.IdentityModel.Tokens/TokenValidationParameters.cs b/src/Microsoft.IdentityModel.Tokens/TokenValidationParameters.cs
index cf40db0b45..c98a01afdd 100644
--- a/src/Microsoft.IdentityModel.Tokens/TokenValidationParameters.cs
+++ b/src/Microsoft.IdentityModel.Tokens/TokenValidationParameters.cs
@@ -189,6 +189,7 @@ public class TokenValidationParameters
private TimeSpan _clockSkew = DefaultClockSkew;
private string _nameClaimType = ClaimsIdentity.DefaultNameClaimType;
private string _roleClaimType = ClaimsIdentity.DefaultRoleClaimType;
+ private Dictionary _instancePropertyBag;
///
/// This is the default value of when creating a .
@@ -483,7 +484,7 @@ public virtual ClaimsIdentity CreateClaimsIdentity(SecurityToken securityToken,
/// Gets a that is unique to this instance.
/// Calling will result in a new instance of this IDictionary.
///
- public IDictionary InstancePropertyBag { get; } = new Dictionary();
+ public IDictionary InstancePropertyBag => _instancePropertyBag ??= new Dictionary();
///
/// Gets a value indicating if was called to obtain this instance.
diff --git a/src/Microsoft.IdentityModel.Tokens/Utility.cs b/src/Microsoft.IdentityModel.Tokens/Utility.cs
index b9f53cf9b8..49e2a3d059 100644
--- a/src/Microsoft.IdentityModel.Tokens/Utility.cs
+++ b/src/Microsoft.IdentityModel.Tokens/Utility.cs
@@ -133,27 +133,25 @@ public static bool IsHttps(Uri uri)
///
/// true if the bytes are equal, false otherwise.
///
- [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)]
+ [MethodImpl(MethodImplOptions.NoInlining)]
public static bool AreEqual(byte[] a, byte[] b)
{
- byte[] s_bytesA = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 };
- byte[] s_bytesB = new byte[] { 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
-
- int result = 0;
- byte[] a1, a2;
+ ReadOnlySpan a1, a2;
if (((a == null) || (b == null))
|| (a.Length != b.Length))
{
- a1 = s_bytesA;
- a2 = s_bytesB;
+ // Non-allocating. The direct assignment into a ReadOnlySpan causes the C# compiler to emit these as pointers into the assembly's data section.
+ a1 = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 };
+ a2 = new byte[] { 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
}
else
{
- a1 = a;
- a2 = b;
+ a1 = a.AsSpan();
+ a2 = b.AsSpan();
}
+ int result = 0;
for (int i = 0; i < a1.Length; i++)
{
result |= a1[i] ^ a2[i];
@@ -163,7 +161,7 @@ public static bool AreEqual(byte[] a, byte[] b)
}
///
- /// Compares two byte arrays for equality. Hash size is fixed normally it is 32 bytes.
+ /// Compares two byte spans for equality. Hash size is fixed normally it is 32 bytes.
/// The attempt here is to take the same time if an attacker shortens the signature OR changes some of the signed contents.
///
///
@@ -172,37 +170,29 @@ public static bool AreEqual(byte[] a, byte[] b)
///
/// The other set of bytes to compare with.
///
- /// length of array to check
+ /// length of spans to check
///
/// true if the bytes are equal, false otherwise.
///
- [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)]
- internal static bool AreEqual(byte[] a, byte[] b, int length)
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ internal static bool AreEqual(ReadOnlySpan a, ReadOnlySpan b, int length)
{
- byte[] s_bytesA = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 };
- byte[] s_bytesB = new byte[] { 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
-
- int result = 0;
- int lenToUse = 0;
- byte[] a1, a2;
-
- if (((a == null) || (b == null))
- || (a.Length < length || b.Length < length))
+ if ((a.Length < length || b.Length < length))
{
- a1 = s_bytesA;
- a2 = s_bytesB;
- lenToUse = a1.Length;
+ // Non-allocating. The direct assignment into a ReadOnlySpan causes the C# compiler to emit these as pointers into the assembly's data section.
+ a = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 };
+ b = new byte[] { 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
}
else
{
- a1 = a;
- a2 = b;
- lenToUse = length;
+ a = a.Slice(0, length);
+ b = b.Slice(0, length);
}
- for (int i = 0; i < lenToUse; i++)
+ int result = 0;
+ for (int i = 0; i < a.Length; i++)
{
- result |= a1[i] ^ a2[i];
+ result |= a[i] ^ b[i];
}
return result == 0;
@@ -251,10 +241,16 @@ internal static void Zero(byte[] byteArray)
internal static byte[] GenerateSha256Hash(string input)
{
+ byte[] bytes = Encoding.UTF8.GetBytes(input);
+
+#if NET6_0_OR_GREATER
+ return SHA256.HashData(bytes);
+#else
using (var hash = SHA256.Create())
{
- return hash.ComputeHash(Encoding.UTF8.GetBytes(input));
+ return hash.ComputeHash(bytes);
}
+#endif
}
}
}
diff --git a/src/Microsoft.IdentityModel.Tokens/opensource/json/Bson/BsonBinaryType.cs b/src/Microsoft.IdentityModel.Tokens/opensource/json/Bson/BsonBinaryType.cs
deleted file mode 100644
index 4339a46b40..0000000000
--- a/src/Microsoft.IdentityModel.Tokens/opensource/json/Bson/BsonBinaryType.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-#region License
-// Copyright (c) 2007 James Newton-King
-//
-// Permission is hereby granted, free of charge, to any person
-// obtaining a copy of this software and associated documentation
-// files (the "Software"), to deal in the Software without
-// restriction, including without limitation the rights to use,
-// copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following
-// conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-// OTHER DEALINGS IN THE SOFTWARE.
-#endregion
-
-using System;
-
-#nullable disable
-
-namespace Microsoft.IdentityModel.Json.Bson
-{
- internal enum BsonBinaryType : byte
- {
- Binary = 0x00,
- Function = 0x01,
-
- [Obsolete("This type has been deprecated in the BSON specification. Use Binary instead.")]
- BinaryOld = 0x02,
-
- [Obsolete("This type has been deprecated in the BSON specification. Use Uuid instead.")]
- UuidOld = 0x03,
- Uuid = 0x04,
- Md5 = 0x05,
- UserDefined = 0x80
- }
-}
diff --git a/src/Microsoft.IdentityModel.Tokens/opensource/json/Bson/BsonBinaryWriter.cs b/src/Microsoft.IdentityModel.Tokens/opensource/json/Bson/BsonBinaryWriter.cs
deleted file mode 100644
index db528596c7..0000000000
--- a/src/Microsoft.IdentityModel.Tokens/opensource/json/Bson/BsonBinaryWriter.cs
+++ /dev/null
@@ -1,330 +0,0 @@
-#region License
-// Copyright (c) 2007 James Newton-King
-//
-// Permission is hereby granted, free of charge, to any person
-// obtaining a copy of this software and associated documentation
-// files (the "Software"), to deal in the Software without
-// restriction, including without limitation the rights to use,
-// copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following
-// conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-// OTHER DEALINGS IN THE SOFTWARE.
-#endregion
-
-using System;
-using System.Globalization;
-using System.IO;
-using System.Text;
-using Microsoft.IdentityModel.Json.Utilities;
-
-#nullable disable
-
-namespace Microsoft.IdentityModel.Json.Bson
-{
- internal class BsonBinaryWriter
- {
- private static readonly Encoding Encoding = new UTF8Encoding(false);
-
- private readonly BinaryWriter _writer;
-
- private byte[] _largeByteBuffer;
-
- public DateTimeKind DateTimeKindHandling { get; set; }
-
- public BsonBinaryWriter(BinaryWriter writer)
- {
- DateTimeKindHandling = DateTimeKind.Utc;
- _writer = writer;
- }
-
- public void Flush()
- {
- _writer.Flush();
- }
-
- public void Close()
- {
-#if HAVE_STREAM_READER_WRITER_CLOSE
- _writer.Close();
-#else
- _writer.Dispose();
-#endif
- }
-
- public void WriteToken(BsonToken t)
- {
- CalculateSize(t);
- WriteTokenInternal(t);
- }
-
- private void WriteTokenInternal(BsonToken t)
- {
- switch (t.Type)
- {
- case BsonType.Object:
- {
- BsonObject value = (BsonObject)t;
- _writer.Write(value.CalculatedSize);
- foreach (BsonProperty property in value)
- {
- _writer.Write((sbyte)property.Value.Type);
- WriteString((string)property.Name.Value, property.Name.ByteCount, null);
- WriteTokenInternal(property.Value);
- }
- _writer.Write((byte)0);
- }
- break;
- case BsonType.Array:
- {
- BsonArray value = (BsonArray)t;
- _writer.Write(value.CalculatedSize);
- ulong index = 0;
- foreach (BsonToken c in value)
- {
- _writer.Write((sbyte)c.Type);
- WriteString(index.ToString(CultureInfo.InvariantCulture), MathUtils.IntLength(index), null);
- WriteTokenInternal(c);
- index++;
- }
- _writer.Write((byte)0);
- }
- break;
- case BsonType.Integer:
- {
- BsonValue value = (BsonValue)t;
- _writer.Write(Convert.ToInt32(value.Value, CultureInfo.InvariantCulture));
- }
- break;
- case BsonType.Long:
- {
- BsonValue value = (BsonValue)t;
- _writer.Write(Convert.ToInt64(value.Value, CultureInfo.InvariantCulture));
- }
- break;
- case BsonType.Number:
- {
- BsonValue value = (BsonValue)t;
- _writer.Write(Convert.ToDouble(value.Value, CultureInfo.InvariantCulture));
- }
- break;
- case BsonType.String:
- {
- BsonString value = (BsonString)t;
- WriteString((string)value.Value, value.ByteCount, value.CalculatedSize - 4);
- }
- break;
- case BsonType.Boolean:
- _writer.Write(t == BsonBoolean.True);
- break;
- case BsonType.Null:
- case BsonType.Undefined:
- break;
- case BsonType.Date:
- {
- BsonValue value = (BsonValue)t;
-
- long ticks = 0;
-
- if (value.Value is DateTime dateTime)
- {
- if (DateTimeKindHandling == DateTimeKind.Utc)
- {
- dateTime = dateTime.ToUniversalTime();
- }
- else if (DateTimeKindHandling == DateTimeKind.Local)
- {
- dateTime = dateTime.ToLocalTime();
- }
-
- ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(dateTime, false);
- }
-#if HAVE_DATE_TIME_OFFSET
- else
- {
- DateTimeOffset dateTimeOffset = (DateTimeOffset)value.Value;
- ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(dateTimeOffset.UtcDateTime, dateTimeOffset.Offset);
- }
-#endif
-
- _writer.Write(ticks);
- }
- break;
- case BsonType.Binary:
- {
- BsonBinary value = (BsonBinary)t;
-
- byte[] data = (byte[])value.Value;
- _writer.Write(data.Length);
- _writer.Write((byte)value.BinaryType);
- _writer.Write(data);
- }
- break;
- case BsonType.Oid:
- {
- BsonValue value = (BsonValue)t;
-
- byte[] data = (byte[])value.Value;
- _writer.Write(data);
- }
- break;
- case BsonType.Regex:
- {
- BsonRegex value = (BsonRegex)t;
-
- WriteString((string)value.Pattern.Value, value.Pattern.ByteCount, null);
- WriteString((string)value.Options.Value, value.Options.ByteCount, null);
- }
- break;
- default:
- throw new ArgumentOutOfRangeException(nameof(t), "Unexpected token when writing BSON: {0}".FormatWith(CultureInfo.InvariantCulture, t.Type));
- }
- }
-
- private void WriteString(string s, int byteCount, int? calculatedlengthPrefix)
- {
- if (calculatedlengthPrefix != null)
- {
- _writer.Write(calculatedlengthPrefix.GetValueOrDefault());
- }
-
- WriteUtf8Bytes(s, byteCount);
-
- _writer.Write((byte)0);
- }
-
- public void WriteUtf8Bytes(string s, int byteCount)
- {
- if (s != null)
- {
- if (byteCount <= 256)
- {
- if (_largeByteBuffer == null)
- {
- _largeByteBuffer = new byte[256];
- }
-
- Encoding.GetBytes(s, 0, s.Length, _largeByteBuffer, 0);
- _writer.Write(_largeByteBuffer, 0, byteCount);
- }
- else
- {
- byte[] bytes = Encoding.GetBytes(s);
- _writer.Write(bytes);
- }
- }
- }
-
- private int CalculateSize(int stringByteCount)
- {
- return stringByteCount + 1;
- }
-
- private int CalculateSizeWithLength(int stringByteCount, bool includeSize)
- {
- int baseSize = (includeSize)
- ? 5 // size bytes + terminator
- : 1; // terminator
-
- return baseSize + stringByteCount;
- }
-
- private int CalculateSize(BsonToken t)
- {
- switch (t.Type)
- {
- case BsonType.Object:
- {
- BsonObject value = (BsonObject)t;
-
- int bases = 4;
- foreach (BsonProperty p in value)
- {
- int size = 1;
- size += CalculateSize(p.Name);
- size += CalculateSize(p.Value);
-
- bases += size;
- }
- bases += 1;
- value.CalculatedSize = bases;
- return bases;
- }
- case BsonType.Array:
- {
- BsonArray value = (BsonArray)t;
-
- int size = 4;
- ulong index = 0;
- foreach (BsonToken c in value)
- {
- size += 1;
- size += CalculateSize(MathUtils.IntLength(index));
- size += CalculateSize(c);
- index++;
- }
- size += 1;
- value.CalculatedSize = size;
-
- return value.CalculatedSize;
- }
- case BsonType.Integer:
- return 4;
- case BsonType.Long:
- return 8;
- case BsonType.Number:
- return 8;
- case BsonType.String:
- {
- BsonString value = (BsonString)t;
- string s = (string)value.Value;
- value.ByteCount = (s != null) ? Encoding.GetByteCount(s) : 0;
- value.CalculatedSize = CalculateSizeWithLength(value.ByteCount, value.IncludeLength);
-
- return value.CalculatedSize;
- }
- case BsonType.Boolean:
- return 1;
- case BsonType.Null:
- case BsonType.Undefined:
- return 0;
- case BsonType.Date:
- return 8;
- case BsonType.Binary:
- {
- BsonBinary value = (BsonBinary)t;
-
- byte[] data = (byte[])value.Value;
- value.CalculatedSize = 4 + 1 + data.Length;
-
- return value.CalculatedSize;
- }
- case BsonType.Oid:
- return 12;
- case BsonType.Regex:
- {
- BsonRegex value = (BsonRegex)t;
- int size = 0;
- size += CalculateSize(value.Pattern);
- size += CalculateSize(value.Options);
- value.CalculatedSize = size;
-
- return value.CalculatedSize;
- }
- default:
- throw new ArgumentOutOfRangeException(nameof(t), "Unexpected token when writing BSON: {0}".FormatWith(CultureInfo.InvariantCulture, t.Type));
- }
- }
- }
-}
diff --git a/src/Microsoft.IdentityModel.Tokens/opensource/json/Bson/BsonObjectId.cs b/src/Microsoft.IdentityModel.Tokens/opensource/json/Bson/BsonObjectId.cs
deleted file mode 100644
index 6ba12b3bca..0000000000
--- a/src/Microsoft.IdentityModel.Tokens/opensource/json/Bson/BsonObjectId.cs
+++ /dev/null
@@ -1,60 +0,0 @@
-#region License
-// Copyright (c) 2007 James Newton-King
-//
-// Permission is hereby granted, free of charge, to any person
-// obtaining a copy of this software and associated documentation
-// files (the "Software"), to deal in the Software without
-// restriction, including without limitation the rights to use,
-// copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following
-// conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-// OTHER DEALINGS IN THE SOFTWARE.
-#endregion
-
-using System;
-using Microsoft.IdentityModel.Json.Utilities;
-
-#nullable disable
-
-namespace Microsoft.IdentityModel.Json.Bson
-{
- ///
- /// Represents a BSON Oid (object id).
- ///
- [Obsolete("BSON reading and writing has been moved to its own package. See https://www.nuget.org/packages/Microsoft.IdentityModel.Json.Bson for more details.")]
- internal class BsonObjectId
- {
- ///
- /// Gets or sets the value of the Oid.
- ///
- /// The value of the Oid.
- public byte[] Value { get; }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The Oid value.
- public BsonObjectId(byte[] value)
- {
- ValidationUtils.ArgumentNotNull(value, nameof(value));
- if (value.Length != 12)
- {
- throw new ArgumentException("An ObjectId must be 12 bytes", nameof(value));
- }
-
- Value = value;
- }
- }
-}
diff --git a/src/Microsoft.IdentityModel.Tokens/opensource/json/Bson/BsonReader.cs b/src/Microsoft.IdentityModel.Tokens/opensource/json/Bson/BsonReader.cs
deleted file mode 100644
index a69af510ea..0000000000
--- a/src/Microsoft.IdentityModel.Tokens/opensource/json/Bson/BsonReader.cs
+++ /dev/null
@@ -1,836 +0,0 @@
-#region License
-// Copyright (c) 2007 James Newton-King
-//
-// Permission is hereby granted, free of charge, to any person
-// obtaining a copy of this software and associated documentation
-// files (the "Software"), to deal in the Software without
-// restriction, including without limitation the rights to use,
-// copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following
-// conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-// OTHER DEALINGS IN THE SOFTWARE.
-#endregion
-
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Text;
-using System.IO;
-using Microsoft.IdentityModel.Json.Serialization;
-using Microsoft.IdentityModel.Json.Utilities;
-using Microsoft.IdentityModel.Json.Linq;
-
-#nullable disable
-
-namespace Microsoft.IdentityModel.Json.Bson
-{
- ///
- /// Represents a reader that provides fast, non-cached, forward-only access to serialized BSON data.
- ///
- [Obsolete("BSON reading and writing has been moved to its own package. See https://www.nuget.org/packages/Microsoft.IdentityModel.Json.Bson for more details.")]
- internal class BsonReader : JsonReader
- {
- private const int MaxCharBytesSize = 128;
- private static readonly byte[] SeqRange1 = new byte[] { 0, 127 }; // range of 1-byte sequence
- private static readonly byte[] SeqRange2 = new byte[] { 194, 223 }; // range of 2-byte sequence
- private static readonly byte[] SeqRange3 = new byte[] { 224, 239 }; // range of 3-byte sequence
- private static readonly byte[] SeqRange4 = new byte[] { 240, 244 }; // range of 4-byte sequence
-
- private readonly BinaryReader _reader;
- private readonly List _stack;
-
- private byte[] _byteBuffer;
- private char[] _charBuffer;
-
- private BsonType _currentElementType;
- private BsonReaderState _bsonReaderState;
- private ContainerContext _currentContext;
-
- private bool _readRootValueAsArray;
- private bool _jsonNet35BinaryCompatibility;
- private DateTimeKind _dateTimeKindHandling;
-
- private enum BsonReaderState
- {
- Normal = 0,
- ReferenceStart = 1,
- ReferenceRef = 2,
- ReferenceId = 3,
- CodeWScopeStart = 4,
- CodeWScopeCode = 5,
- CodeWScopeScope = 6,
- CodeWScopeScopeObject = 7,
- CodeWScopeScopeEnd = 8
- }
-
- private class ContainerContext
- {
- public readonly BsonType Type;
- public int Length;
- public int Position;
-
- public ContainerContext(BsonType type)
- {
- Type = type;
- }
- }
-
- ///
- /// Gets or sets a value indicating whether binary data reading should be compatible with incorrect Json.NET 3.5 written binary.
- ///
- ///
- /// true if binary data reading will be compatible with incorrect Json.NET 3.5 written binary; otherwise, false.
- ///
- [Obsolete("JsonNet35BinaryCompatibility will be removed in a future version of Json.NET.")]
- public bool JsonNet35BinaryCompatibility
- {
- get => _jsonNet35BinaryCompatibility;
- set => _jsonNet35BinaryCompatibility = value;
- }
-
- ///
- /// Gets or sets a value indicating whether the root object will be read as a JSON array.
- ///
- ///
- /// true if the root object will be read as a JSON array; otherwise, false.
- ///
- public bool ReadRootValueAsArray
- {
- get => _readRootValueAsArray;
- set => _readRootValueAsArray = value;
- }
-
- ///
- /// Gets or sets the used when reading values from BSON.
- ///
- /// The used when reading values from BSON.
- public DateTimeKind DateTimeKindHandling
- {
- get => _dateTimeKindHandling;
- set => _dateTimeKindHandling = value;
- }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The containing the BSON data to read.
- public BsonReader(Stream stream)
- : this(stream, false, DateTimeKind.Local)
- {
- }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The containing the BSON data to read.
- public BsonReader(BinaryReader reader)
- : this(reader, false, DateTimeKind.Local)
- {
- }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The containing the BSON data to read.
- /// if set to true the root object will be read as a JSON array.
- /// The used when reading values from BSON.
- public BsonReader(Stream stream, bool readRootValueAsArray, DateTimeKind dateTimeKindHandling)
- {
- ValidationUtils.ArgumentNotNull(stream, nameof(stream));
- _reader = new BinaryReader(stream);
- _stack = new List();
- _readRootValueAsArray = readRootValueAsArray;
- _dateTimeKindHandling = dateTimeKindHandling;
- }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The containing the BSON data to read.
- /// if set to true the root object will be read as a JSON array.
- /// The used when reading values from BSON.
- public BsonReader(BinaryReader reader, bool readRootValueAsArray, DateTimeKind dateTimeKindHandling)
- {
- ValidationUtils.ArgumentNotNull(reader, nameof(reader));
- _reader = reader;
- _stack = new List();
- _readRootValueAsArray = readRootValueAsArray;
- _dateTimeKindHandling = dateTimeKindHandling;
- }
-
- private string ReadElement()
- {
- _currentElementType = ReadType();
- string elementName = ReadString();
- return elementName;
- }
-
- ///
- /// Reads the next JSON token from the underlying .
- ///
- ///
- /// true if the next token was read successfully; false if there are no more tokens to read.
- ///
- public override bool Read()
- {
- try
- {
- bool success;
-
- switch (_bsonReaderState)
- {
- case BsonReaderState.Normal:
- success = ReadNormal();
- break;
- case BsonReaderState.ReferenceStart:
- case BsonReaderState.ReferenceRef:
- case BsonReaderState.ReferenceId:
- success = ReadReference();
- break;
- case BsonReaderState.CodeWScopeStart:
- case BsonReaderState.CodeWScopeCode:
- case BsonReaderState.CodeWScopeScope:
- case BsonReaderState.CodeWScopeScopeObject:
- case BsonReaderState.CodeWScopeScopeEnd:
- success = ReadCodeWScope();
- break;
- default:
- throw JsonReaderException.Create(this, "Unexpected state: {0}".FormatWith(CultureInfo.InvariantCulture, _bsonReaderState));
- }
-
- if (!success)
- {
- SetToken(JsonToken.None);
- return false;
- }
-
- return true;
- }
- catch (EndOfStreamException)
- {
- SetToken(JsonToken.None);
- return false;
- }
- }
-
- ///
- /// Changes the reader's state to .
- /// If is set to true, the underlying is also closed.
- ///
- public override void Close()
- {
- base.Close();
-
- if (CloseInput)
- {
-#if HAVE_STREAM_READER_WRITER_CLOSE
- _reader?.Close();
-#else
- _reader?.Dispose();
-#endif
- }
- }
-
- private bool ReadCodeWScope()
- {
- switch (_bsonReaderState)
- {
- case BsonReaderState.CodeWScopeStart:
- SetToken(JsonToken.PropertyName, "$code");
- _bsonReaderState = BsonReaderState.CodeWScopeCode;
- return true;
- case BsonReaderState.CodeWScopeCode:
- // total CodeWScope size - not used
- ReadInt32();
-
- SetToken(JsonToken.String, ReadLengthString());
- _bsonReaderState = BsonReaderState.CodeWScopeScope;
- return true;
- case BsonReaderState.CodeWScopeScope:
- if (CurrentState == State.PostValue)
- {
- SetToken(JsonToken.PropertyName, "$scope");
- return true;
- }
- else
- {
- SetToken(JsonToken.StartObject);
- _bsonReaderState = BsonReaderState.CodeWScopeScopeObject;
-
- ContainerContext newContext = new ContainerContext(BsonType.Object);
- PushContext(newContext);
- newContext.Length = ReadInt32();
-
- return true;
- }
- case BsonReaderState.CodeWScopeScopeObject:
- bool result = ReadNormal();
- if (result && TokenType == JsonToken.EndObject)
- {
- _bsonReaderState = BsonReaderState.CodeWScopeScopeEnd;
- }
-
- return result;
- case BsonReaderState.CodeWScopeScopeEnd:
- SetToken(JsonToken.EndObject);
- _bsonReaderState = BsonReaderState.Normal;
- return true;
- default:
- throw new ArgumentOutOfRangeException();
- }
- }
-
- private bool ReadReference()
- {
- switch (CurrentState)
- {
- case State.ObjectStart:
- {
- SetToken(JsonToken.PropertyName, JsonTypeReflector.RefPropertyName);
- _bsonReaderState = BsonReaderState.ReferenceRef;
- return true;
- }
- case State.Property:
- {
- if (_bsonReaderState == BsonReaderState.ReferenceRef)
- {
- SetToken(JsonToken.String, ReadLengthString());
- return true;
- }
- else if (_bsonReaderState == BsonReaderState.ReferenceId)
- {
- SetToken(JsonToken.Bytes, ReadBytes(12));
- return true;
- }
- else
- {
- throw JsonReaderException.Create(this, "Unexpected state when reading BSON reference: " + _bsonReaderState);
- }
- }
- case State.PostValue:
- {
- if (_bsonReaderState == BsonReaderState.ReferenceRef)
- {
- SetToken(JsonToken.PropertyName, JsonTypeReflector.IdPropertyName);
- _bsonReaderState = BsonReaderState.ReferenceId;
- return true;
- }
- else if (_bsonReaderState == BsonReaderState.ReferenceId)
- {
- SetToken(JsonToken.EndObject);
- _bsonReaderState = BsonReaderState.Normal;
- return true;
- }
- else
- {
- throw JsonReaderException.Create(this, "Unexpected state when reading BSON reference: " + _bsonReaderState);
- }
- }
- default:
- throw JsonReaderException.Create(this, "Unexpected state when reading BSON reference: " + CurrentState);
- }
- }
-
- private bool ReadNormal()
- {
- switch (CurrentState)
- {
- case State.Start:
- {
- JsonToken token = (!_readRootValueAsArray) ? JsonToken.StartObject : JsonToken.StartArray;
- BsonType type = (!_readRootValueAsArray) ? BsonType.Object : BsonType.Array;
-
- SetToken(token);
- ContainerContext newContext = new ContainerContext(type);
- PushContext(newContext);
- newContext.Length = ReadInt32();
- return true;
- }
- case State.Complete:
- case State.Closed:
- return false;
- case State.Property:
- {
- ReadType(_currentElementType);
- return true;
- }
- case State.ObjectStart:
- case State.ArrayStart:
- case State.PostValue:
- ContainerContext context = _currentContext;
- if (context == null)
- {
- if (SupportMultipleContent)
- {
- goto case State.Start;
- }
-
- return false;
- }
-
- int lengthMinusEnd = context.Length - 1;
-
- if (context.Position < lengthMinusEnd)
- {
- if (context.Type == BsonType.Array)
- {
- ReadElement();
- ReadType(_currentElementType);
- return true;
- }
- else
- {
- SetToken(JsonToken.PropertyName, ReadElement());
- return true;
- }
- }
- else if (context.Position == lengthMinusEnd)
- {
- if (ReadByte() != 0)
- {
- throw JsonReaderException.Create(this, "Unexpected end of object byte value.");
- }
-
- PopContext();
- if (_currentContext != null)
- {
- MovePosition(context.Length);
- }
-
- JsonToken endToken = (context.Type == BsonType.Object) ? JsonToken.EndObject : JsonToken.EndArray;
- SetToken(endToken);
- return true;
- }
- else
- {
- throw JsonReaderException.Create(this, "Read past end of current container context.");
- }
- case State.ConstructorStart:
- break;
- case State.Constructor:
- break;
- case State.Error:
- break;
- case State.Finished:
- break;
- default:
- throw new ArgumentOutOfRangeException();
- }
-
- return false;
- }
-
- private void PopContext()
- {
- _stack.RemoveAt(_stack.Count - 1);
- if (_stack.Count == 0)
- {
- _currentContext = null;
- }
- else
- {
- _currentContext = _stack[_stack.Count - 1];
- }
- }
-
- private void PushContext(ContainerContext newContext)
- {
- _stack.Add(newContext);
- _currentContext = newContext;
- }
-
- private byte ReadByte()
- {
- MovePosition(1);
- return _reader.ReadByte();
- }
-
- private void ReadType(BsonType type)
- {
- switch (type)
- {
- case BsonType.Number:
- double d = ReadDouble();
-
- if (_floatParseHandling == FloatParseHandling.Decimal)
- {
- SetToken(JsonToken.Float, Convert.ToDecimal(d, CultureInfo.InvariantCulture));
- }
- else
- {
- SetToken(JsonToken.Float, d);
- }
- break;
- case BsonType.String:
- case BsonType.Symbol:
- SetToken(JsonToken.String, ReadLengthString());
- break;
- case BsonType.Object:
- {
- SetToken(JsonToken.StartObject);
-
- ContainerContext newContext = new ContainerContext(BsonType.Object);
- PushContext(newContext);
- newContext.Length = ReadInt32();
- break;
- }
- case BsonType.Array:
- {
- SetToken(JsonToken.StartArray);
-
- ContainerContext newContext = new ContainerContext(BsonType.Array);
- PushContext(newContext);
- newContext.Length = ReadInt32();
- break;
- }
- case BsonType.Binary:
- BsonBinaryType binaryType;
- byte[] data = ReadBinary(out binaryType);
-
- object value = (binaryType != BsonBinaryType.Uuid)
- ? data
- : (object)new Guid(data);
-
- SetToken(JsonToken.Bytes, value);
- break;
- case BsonType.Undefined:
- SetToken(JsonToken.Undefined);
- break;
- case BsonType.Oid:
- byte[] oid = ReadBytes(12);
- SetToken(JsonToken.Bytes, oid);
- break;
- case BsonType.Boolean:
- bool b = Convert.ToBoolean(ReadByte());
- SetToken(JsonToken.Boolean, b);
- break;
- case BsonType.Date:
- long ticks = ReadInt64();
- DateTime utcDateTime = DateTimeUtils.ConvertJavaScriptTicksToDateTime(ticks);
-
- DateTime dateTime;
- switch (DateTimeKindHandling)
- {
- case DateTimeKind.Unspecified:
- dateTime = DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified);
- break;
- case DateTimeKind.Local:
- dateTime = utcDateTime.ToLocalTime();
- break;
- default:
- dateTime = utcDateTime;
- break;
- }
-
- SetToken(JsonToken.Date, dateTime);
- break;
- case BsonType.Null:
- SetToken(JsonToken.Null);
- break;
- case BsonType.Regex:
- string expression = ReadString();
- string modifiers = ReadString();
-
- string regex = @"/" + expression + @"/" + modifiers;
- SetToken(JsonToken.String, regex);
- break;
- case BsonType.Reference:
- SetToken(JsonToken.StartObject);
- _bsonReaderState = BsonReaderState.ReferenceStart;
- break;
- case BsonType.Code:
- SetToken(JsonToken.String, ReadLengthString());
- break;
- case BsonType.CodeWScope:
- SetToken(JsonToken.StartObject);
- _bsonReaderState = BsonReaderState.CodeWScopeStart;
- break;
- case BsonType.Integer:
- SetToken(JsonToken.Integer, (long)ReadInt32());
- break;
- case BsonType.TimeStamp:
- case BsonType.Long:
- SetToken(JsonToken.Integer, ReadInt64());
- break;
- default:
- throw new ArgumentOutOfRangeException(nameof(type), "Unexpected BsonType value: " + type);
- }
- }
-
- private byte[] ReadBinary(out BsonBinaryType binaryType)
- {
- int dataLength = ReadInt32();
-
- binaryType = (BsonBinaryType)ReadByte();
-
-#pragma warning disable 612,618
- // the old binary type has the data length repeated in the data for some reason
- if (binaryType == BsonBinaryType.BinaryOld && !_jsonNet35BinaryCompatibility)
- {
- dataLength = ReadInt32();
- }
-#pragma warning restore 612,618
-
- return ReadBytes(dataLength);
- }
-
- private string ReadString()
- {
- EnsureBuffers();
-
- StringBuilder builder = null;
-
- int totalBytesRead = 0;
- // used in case of left over multibyte characters in the buffer
- int offset = 0;
- while (true)
- {
- int count = offset;
- byte b;
- while (count < MaxCharBytesSize && (b = _reader.ReadByte()) > 0)
- {
- _byteBuffer[count++] = b;
- }
- int byteCount = count - offset;
- totalBytesRead += byteCount;
-
- if (count < MaxCharBytesSize && builder == null)
- {
- // pref optimization to avoid reading into a string builder
- // if string is smaller than the buffer then return it directly
- int length = Encoding.UTF8.GetChars(_byteBuffer, 0, byteCount, _charBuffer, 0);
-
- MovePosition(totalBytesRead + 1);
- return new string(_charBuffer, 0, length);
- }
- else
- {
- // calculate the index of the end of the last full character in the buffer
- int lastFullCharStop = GetLastFullCharStop(count - 1);
-
- int charCount = Encoding.UTF8.GetChars(_byteBuffer, 0, lastFullCharStop + 1, _charBuffer, 0);
-
- if (builder == null)
- {
- builder = new StringBuilder(MaxCharBytesSize * 2);
- }
-
- builder.Append(_charBuffer, 0, charCount);
-
- if (lastFullCharStop < byteCount - 1)
- {
- offset = byteCount - lastFullCharStop - 1;
- // copy left over multi byte characters to beginning of buffer for next iteration
- Array.Copy(_byteBuffer, lastFullCharStop + 1, _byteBuffer, 0, offset);
- }
- else
- {
- // reached end of string
- if (count < MaxCharBytesSize)
- {
- MovePosition(totalBytesRead + 1);
- return builder.ToString();
- }
-
- offset = 0;
- }
- }
- }
- }
-
- private string ReadLengthString()
- {
- int length = ReadInt32();
-
- MovePosition(length);
-
- string s = GetString(length - 1);
- _reader.ReadByte();
-
- return s;
- }
-
- private string GetString(int length)
- {
- if (length == 0)
- {
- return string.Empty;
- }
-
- EnsureBuffers();
-
- StringBuilder builder = null;
-
- int totalBytesRead = 0;
-
- // used in case of left over multibyte characters in the buffer
- int offset = 0;
- do
- {
- int count = ((length - totalBytesRead) > MaxCharBytesSize - offset)
- ? MaxCharBytesSize - offset
- : length - totalBytesRead;
-
- int byteCount = _reader.Read(_byteBuffer, offset, count);
-
- if (byteCount == 0)
- {
- throw new EndOfStreamException("Unable to read beyond the end of the stream.");
- }
-
- totalBytesRead += byteCount;
-
- // Above, byteCount is how many bytes we read this time.
- // Below, byteCount is how many bytes are in the _byteBuffer.
- byteCount += offset;
-
- if (byteCount == length)
- {
- // pref optimization to avoid reading into a string builder
- // first iteration and all bytes read then return string directly
- int charCount = Encoding.UTF8.GetChars(_byteBuffer, 0, byteCount, _charBuffer, 0);
- return new string(_charBuffer, 0, charCount);
- }
- else
- {
- int lastFullCharStop = GetLastFullCharStop(byteCount - 1);
-
- if (builder == null)
- {
- builder = new StringBuilder(length);
- }
-
- int charCount = Encoding.UTF8.GetChars(_byteBuffer, 0, lastFullCharStop + 1, _charBuffer, 0);
- builder.Append(_charBuffer, 0, charCount);
-
- if (lastFullCharStop < byteCount - 1)
- {
- offset = byteCount - lastFullCharStop - 1;
- // copy left over multi byte characters to beginning of buffer for next iteration
- Array.Copy(_byteBuffer, lastFullCharStop + 1, _byteBuffer, 0, offset);
- }
- else
- {
- offset = 0;
- }
- }
- } while (totalBytesRead < length);
-
- return builder.ToString();
- }
-
- private int GetLastFullCharStop(int start)
- {
- int lookbackPos = start;
- int bis = 0;
- while (lookbackPos >= 0)
- {
- bis = BytesInSequence(_byteBuffer[lookbackPos]);
- if (bis == 0)
- {
- lookbackPos--;
- continue;
- }
- else if (bis == 1)
- {
- break;
- }
- else
- {
- lookbackPos--;
- break;
- }
- }
- if (bis == start - lookbackPos)
- {
- //Full character.
- return start;
- }
- else
- {
- return lookbackPos;
- }
- }
-
- private int BytesInSequence(byte b)
- {
- if (b <= SeqRange1[1])
- {
- return 1;
- }
- if (b >= SeqRange2[0] && b <= SeqRange2[1])
- {
- return 2;
- }
- if (b >= SeqRange3[0] && b <= SeqRange3[1])
- {
- return 3;
- }
- if (b >= SeqRange4[0] && b <= SeqRange4[1])
- {
- return 4;
- }
- return 0;
- }
-
- private void EnsureBuffers()
- {
- if (_byteBuffer == null)
- {
- _byteBuffer = new byte[MaxCharBytesSize];
- }
- if (_charBuffer == null)
- {
- int charBufferSize = Encoding.UTF8.GetMaxCharCount(MaxCharBytesSize);
- _charBuffer = new char[charBufferSize];
- }
- }
-
- private double ReadDouble()
- {
- MovePosition(8);
- return _reader.ReadDouble();
- }
-
- private int ReadInt32()
- {
- MovePosition(4);
- return _reader.ReadInt32();
- }
-
- private long ReadInt64()
- {
- MovePosition(8);
- return _reader.ReadInt64();
- }
-
- private BsonType ReadType()
- {
- MovePosition(1);
- return (BsonType)_reader.ReadSByte();
- }
-
- private void MovePosition(int count)
- {
- _currentContext.Position += count;
- }
-
- private byte[] ReadBytes(int count)
- {
- MovePosition(count);
- return _reader.ReadBytes(count);
- }
- }
-}
diff --git a/src/Microsoft.IdentityModel.Tokens/opensource/json/Bson/BsonToken.cs b/src/Microsoft.IdentityModel.Tokens/opensource/json/Bson/BsonToken.cs
deleted file mode 100644
index 46baeed080..0000000000
--- a/src/Microsoft.IdentityModel.Tokens/opensource/json/Bson/BsonToken.cs
+++ /dev/null
@@ -1,168 +0,0 @@
-#region License
-// Copyright (c) 2007 James Newton-King
-//
-// Permission is hereby granted, free of charge, to any person
-// obtaining a copy of this software and associated documentation
-// files (the "Software"), to deal in the Software without
-// restriction, including without limitation the rights to use,
-// copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following
-// conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-// OTHER DEALINGS IN THE SOFTWARE.
-#endregion
-
-using System.Collections;
-using System.Collections.Generic;
-
-#nullable disable
-
-namespace Microsoft.IdentityModel.Json.Bson
-{
- internal abstract class BsonToken
- {
- public abstract BsonType Type { get; }
- public BsonToken Parent { get; set; }
- public int CalculatedSize { get; set; }
- }
-
- internal class BsonObject : BsonToken, IEnumerable
- {
- private readonly List _children = new List();
-
- public void Add(string name, BsonToken token)
- {
- _children.Add(new BsonProperty { Name = new BsonString(name, false), Value = token });
- token.Parent = this;
- }
-
- public override BsonType Type => BsonType.Object;
-
- public IEnumerator GetEnumerator()
- {
- return _children.GetEnumerator();
- }
-
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
- }
-
- internal class BsonArray : BsonToken, IEnumerable
- {
- private readonly List _children = new List();
-
- public void Add(BsonToken token)
- {
- _children.Add(token);
- token.Parent = this;
- }
-
- public override BsonType Type => BsonType.Array;
-
- public IEnumerator GetEnumerator()
- {
- return _children.GetEnumerator();
- }
-
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
- }
-
- internal class BsonEmpty : BsonToken
- {
- public static readonly BsonToken Null = new BsonEmpty(BsonType.Null);
- public static readonly BsonToken Undefined = new BsonEmpty(BsonType.Undefined);
-
- private BsonEmpty(BsonType type)
- {
- Type = type;
- }
-
- public override BsonType Type { get; }
- }
-
- internal class BsonValue : BsonToken
- {
- private readonly object _value;
- private readonly BsonType _type;
-
- public BsonValue(object value, BsonType type)
- {
- _value = value;
- _type = type;
- }
-
- public object Value => _value;
-
- public override BsonType Type => _type;
- }
-
- internal class BsonBoolean : BsonValue
- {
- public static readonly BsonBoolean False = new BsonBoolean(false);
- public static readonly BsonBoolean True = new BsonBoolean(true);
-
- private BsonBoolean(bool value)
- : base(value, BsonType.Boolean)
- {
- }
- }
-
- internal class BsonString : BsonValue
- {
- public int ByteCount { get; set; }
- public bool IncludeLength { get; }
-
- public BsonString(object value, bool includeLength)
- : base(value, BsonType.String)
- {
- IncludeLength = includeLength;
- }
- }
-
- internal class BsonBinary : BsonValue
- {
- public BsonBinaryType BinaryType { get; set; }
-
- public BsonBinary(byte[] value, BsonBinaryType binaryType)
- : base(value, BsonType.Binary)
- {
- BinaryType = binaryType;
- }
- }
-
- internal class BsonRegex : BsonToken
- {
- public BsonString Pattern { get; set; }
- public BsonString Options { get; set; }
-
- public BsonRegex(string pattern, string options)
- {
- Pattern = new BsonString(pattern, false);
- Options = new BsonString(options, false);
- }
-
- public override BsonType Type => BsonType.Regex;
- }
-
- internal class BsonProperty
- {
- public BsonString Name { get; set; }
- public BsonToken Value { get; set; }
- }
-}
diff --git a/src/Microsoft.IdentityModel.Tokens/opensource/json/Bson/BsonType.cs b/src/Microsoft.IdentityModel.Tokens/opensource/json/Bson/BsonType.cs
deleted file mode 100644
index 9861a871cf..0000000000
--- a/src/Microsoft.IdentityModel.Tokens/opensource/json/Bson/BsonType.cs
+++ /dev/null
@@ -1,53 +0,0 @@
-#region License
-// Copyright (c) 2007 James Newton-King
-//
-// Permission is hereby granted, free of charge, to any person
-// obtaining a copy of this software and associated documentation
-// files (the "Software"), to deal in the Software without
-// restriction, including without limitation the rights to use,
-// copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following
-// conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-// OTHER DEALINGS IN THE SOFTWARE.
-#endregion
-
-#nullable disable
-
-namespace Microsoft.IdentityModel.Json.Bson
-{
- internal enum BsonType : sbyte
- {
- Number = 1,
- String = 2,
- Object = 3,
- Array = 4,
- Binary = 5,
- Undefined = 6,
- Oid = 7,
- Boolean = 8,
- Date = 9,
- Null = 10,
- Regex = 11,
- Reference = 12,
- Code = 13,
- Symbol = 14,
- CodeWScope = 15,
- Integer = 16,
- TimeStamp = 17,
- Long = 18,
- MinKey = -1,
- MaxKey = 127
- }
-}
diff --git a/src/Microsoft.IdentityModel.Tokens/opensource/json/Bson/BsonWriter.cs b/src/Microsoft.IdentityModel.Tokens/opensource/json/Bson/BsonWriter.cs
deleted file mode 100644
index 279007125a..0000000000
--- a/src/Microsoft.IdentityModel.Tokens/opensource/json/Bson/BsonWriter.cs
+++ /dev/null
@@ -1,539 +0,0 @@
-#region License
-// Copyright (c) 2007 James Newton-King
-//
-// Permission is hereby granted, free of charge, to any person
-// obtaining a copy of this software and associated documentation
-// files (the "Software"), to deal in the Software without
-// restriction, including without limitation the rights to use,
-// copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following
-// conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-// OTHER DEALINGS IN THE SOFTWARE.
-#endregion
-
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.IO;
-#if HAVE_BIG_INTEGER
-using System.Numerics;
-#endif
-using System.Text;
-using Microsoft.IdentityModel.Json.Utilities;
-using Microsoft.IdentityModel.Json.Linq;
-using System.Globalization;
-
-#nullable disable
-
-namespace Microsoft.IdentityModel.Json.Bson
-{
- ///
- /// Represents a writer that provides a fast, non-cached, forward-only way of generating BSON data.
- ///
- [Obsolete("BSON reading and writing has been moved to its own package. See https://www.nuget.org/packages/Microsoft.IdentityModel.Json.Bson for more details.")]
- internal class BsonWriter : JsonWriter
- {
- private readonly BsonBinaryWriter _writer;
-
- private BsonToken _root;
- private BsonToken _parent;
- private string _propertyName;
-
- ///
- /// Gets or sets the used when writing values to BSON.
- /// When set to no conversion will occur.
- ///
- /// The used when writing values to BSON.
- public DateTimeKind DateTimeKindHandling
- {
- get => _writer.DateTimeKindHandling;
- set => _writer.DateTimeKindHandling = value;
- }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The to write to.
- public BsonWriter(Stream stream)
- {
- ValidationUtils.ArgumentNotNull(stream, nameof(stream));
- _writer = new BsonBinaryWriter(new BinaryWriter(stream));
- }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The to write to.
- public BsonWriter(BinaryWriter writer)
- {
- ValidationUtils.ArgumentNotNull(writer, nameof(writer));
- _writer = new BsonBinaryWriter(writer);
- }
-
- ///
- /// Flushes whatever is in the buffer to the underlying and also flushes the underlying stream.
- ///
- public override void Flush()
- {
- _writer.Flush();
- }
-
- ///
- /// Writes the end.
- ///
- /// The token.
- protected override void WriteEnd(JsonToken token)
- {
- base.WriteEnd(token);
- RemoveParent();
-
- if (Top == 0)
- {
- _writer.WriteToken(_root);
- }
- }
-
- ///
- /// Writes a comment /*...*/ containing the specified text.
- ///
- /// Text to place inside the comment.
- public override void WriteComment(string text)
- {
- throw JsonWriterException.Create(this, "Cannot write JSON comment as BSON.", null);
- }
-
- ///
- /// Writes the start of a constructor with the given name.
- ///
- /// The name of the constructor.
- public override void WriteStartConstructor(string name)
- {
- throw JsonWriterException.Create(this, "Cannot write JSON constructor as BSON.", null);
- }
-
- ///
- /// Writes raw JSON.
- ///
- /// The raw JSON to write.
- public override void WriteRaw(string json)
- {
- throw JsonWriterException.Create(this, "Cannot write raw JSON as BSON.", null);
- }
-
- ///
- /// Writes raw JSON where a value is expected and updates the writer's state.
- ///
- /// The raw JSON to write.
- public override void WriteRawValue(string json)
- {
- throw JsonWriterException.Create(this, "Cannot write raw JSON as BSON.", null);
- }
-
- ///
- /// Writes the beginning of a JSON array.
- ///
- public override void WriteStartArray()
- {
- base.WriteStartArray();
-
- AddParent(new BsonArray());
- }
-
- ///
- /// Writes the beginning of a JSON object.
- ///
- public override void WriteStartObject()
- {
- base.WriteStartObject();
-
- AddParent(new BsonObject());
- }
-
- ///
- /// Writes the property name of a name/value pair on a JSON object.
- ///
- /// The name of the property.
- public override void WritePropertyName(string name)
- {
- base.WritePropertyName(name);
-
- _propertyName = name;
- }
-
- ///
- /// Closes this writer.
- /// If is set to true, the underlying is also closed.
- /// If is set to true, the JSON is auto-completed.
- ///
- public override void Close()
- {
- base.Close();
-
- if (CloseOutput)
- {
- _writer?.Close();
- }
- }
-
- private void AddParent(BsonToken container)
- {
- AddToken(container);
- _parent = container;
- }
-
- private void RemoveParent()
- {
- _parent = _parent.Parent;
- }
-
- private void AddValue(object value, BsonType type)
- {
- AddToken(new BsonValue(value, type));
- }
-
- internal void AddToken(BsonToken token)
- {
- if (_parent != null)
- {
- if (_parent is BsonObject bo)
- {
- bo.Add(_propertyName, token);
- _propertyName = null;
- }
- else
- {
- ((BsonArray)_parent).Add(token);
- }
- }
- else
- {
- if (token.Type != BsonType.Object && token.Type != BsonType.Array)
- {
- throw JsonWriterException.Create(this, "Error writing {0} value. BSON must start with an Object or Array.".FormatWith(CultureInfo.InvariantCulture, token.Type), null);
- }
-
- _parent = token;
- _root = token;
- }
- }
-
- #region WriteValue methods
- ///
- /// Writes a value.
- /// An error will raised if the value cannot be written as a single JSON token.
- ///
- /// The value to write.
- public override void WriteValue(object value)
- {
-#if HAVE_BIG_INTEGER
- if (value is BigInteger i)
- {
- SetWriteState(JsonToken.Integer, null);
- AddToken(new BsonBinary(i.ToByteArray(), BsonBinaryType.Binary));
- }
- else
-#endif
- {
- base.WriteValue(value);
- }
- }
-
- ///
- /// Writes a null value.
- ///
- public override void WriteNull()
- {
- base.WriteNull();
- AddToken(BsonEmpty.Null);
- }
-
- ///
- /// Writes an undefined value.
- ///
- public override void WriteUndefined()
- {
- base.WriteUndefined();
- AddToken(BsonEmpty.Undefined);
- }
-
- ///
- /// Writes a value.
- ///
- /// The value to write.
- public override void WriteValue(string value)
- {
- base.WriteValue(value);
- AddToken(value == null ? BsonEmpty.Null : new BsonString(value, true));
- }
-
- ///
- /// Writes a value.
- ///
- /// The value to write.
- public override void WriteValue(int value)
- {
- base.WriteValue(value);
- AddValue(value, BsonType.Integer);
- }
-
- ///
- /// Writes a value.
- ///
- /// The value to write.
- // [ClsCompliant(false)]
- public override void WriteValue(uint value)
- {
- if (value > int.MaxValue)
- {
- throw JsonWriterException.Create(this, "Value is too large to fit in a signed 32 bit integer. BSON does not support unsigned values.", null);
- }
-
- base.WriteValue(value);
- AddValue(value, BsonType.Integer);
- }
-
- ///
- /// Writes a value.
- ///
- /// The value to write.
- public override void WriteValue(long value)
- {
- base.WriteValue(value);
- AddValue(value, BsonType.Long);
- }
-
- ///
- /// Writes a value.
- ///
- /// The value to write.
- // [ClsCompliant(false)]
- public override void WriteValue(ulong value)
- {
- if (value > long.MaxValue)
- {
- throw JsonWriterException.Create(this, "Value is too large to fit in a signed 64 bit integer. BSON does not support unsigned values.", null);
- }
-
- base.WriteValue(value);
- AddValue(value, BsonType.Long);
- }
-
- ///
- /// Writes a value.
- ///
- /// The value to write.
- public override void WriteValue(float value)
- {
- base.WriteValue(value);
- AddValue(value, BsonType.Number);
- }
-
- ///
- /// Writes a value.
- ///
- /// The value to write.
- public override void WriteValue(double value)
- {
- base.WriteValue(value);
- AddValue(value, BsonType.Number);
- }
-
- ///
- /// Writes a value.
- ///
- /// The value to write.
- public override void WriteValue(bool value)
- {
- base.WriteValue(value);
- AddToken(value ? BsonBoolean.True : BsonBoolean.False);
- }
-
- ///
- /// Writes a value.
- ///
- /// The value to write.
- public override void WriteValue(short value)
- {
- base.WriteValue(value);
- AddValue(value, BsonType.Integer);
- }
-
- ///
- /// Writes a value.
- ///
- /// The value to write.
- // [ClsCompliant(false)]
- public override void WriteValue(ushort value)
- {
- base.WriteValue(value);
- AddValue(value, BsonType.Integer);
- }
-
- ///
- /// Writes a value.
- ///
- /// The value to write.
- public override void WriteValue(char value)
- {
- base.WriteValue(value);
- string s = null;
-#if HAVE_CHAR_TO_STRING_WITH_CULTURE
- s = value.ToString(CultureInfo.InvariantCulture);
-#else
- s = value.ToString();
-#endif
- AddToken(new BsonString(s, true));
- }
-
- ///
- /// Writes a value.
- ///
- /// The value to write.
- public override void WriteValue(byte value)
- {
- base.WriteValue(value);
- AddValue(value, BsonType.Integer);
- }
-
- ///
- /// Writes a value.
- ///
- /// The value to write.
- // [ClsCompliant(false)]
- public override void WriteValue(sbyte value)
- {
- base.WriteValue(value);
- AddValue(value, BsonType.Integer);
- }
-
- ///
- /// Writes a value.
- ///
- /// The value to write.
- public override void WriteValue(decimal value)
- {
- base.WriteValue(value);
- AddValue(value, BsonType.Number);
- }
-
- ///
- /// Writes a value.
- ///
- /// The value to write.
- public override void WriteValue(DateTime value)
- {
- base.WriteValue(value);
- value = DateTimeUtils.EnsureDateTime(value, DateTimeZoneHandling);
- AddValue(value, BsonType.Date);
- }
-
-#if HAVE_DATE_TIME_OFFSET
- ///
- /// Writes a value.
- ///
- /// The value to write.
- public override void WriteValue(DateTimeOffset value)
- {
- base.WriteValue(value);
- AddValue(value, BsonType.Date);
- }
-#endif
-
- ///
- /// Writes a [] value.
- ///
- /// The [] value to write.
- public override void WriteValue(byte[] value)
- {
- if (value == null)
- {
- WriteNull();
- return;
- }
-
- base.WriteValue(value);
- AddToken(new BsonBinary(value, BsonBinaryType.Binary));
- }
-
- ///
- /// Writes a value.
- ///
- /// The value to write.
- public override void WriteValue(Guid value)
- {
- base.WriteValue(value);
- AddToken(new BsonBinary(value.ToByteArray(), BsonBinaryType.Uuid));
- }
-
- ///
- /// Writes a value.
- ///
- /// The value to write.
- public override void WriteValue(TimeSpan value)
- {
- base.WriteValue(value);
- AddToken(new BsonString(value.ToString(), true));
- }
-
- ///
- /// Writes a value.
- ///
- /// The value to write.
- public override void WriteValue(Uri value)
- {
- if (value == null)
- {
- WriteNull();
- return;
- }
-
- base.WriteValue(value);
- AddToken(new BsonString(value.ToString(), true));
- }
- #endregion
-
- ///
- /// Writes a [] value that represents a BSON object id.
- ///
- /// The Object ID value to write.
- public void WriteObjectId(byte[] value)
- {
- ValidationUtils.ArgumentNotNull(value, nameof(value));
-
- if (value.Length != 12)
- {
- throw JsonWriterException.Create(this, "An object id must be 12 bytes", null);
- }
-
- // hack to update the writer state
- SetWriteState(JsonToken.Undefined, null);
- AddValue(value, BsonType.Oid);
- }
-
- ///
- /// Writes a BSON regex.
- ///
- /// The regex pattern.
- /// The regex options.
- public void WriteRegex(string pattern, string options)
- {
- ValidationUtils.ArgumentNotNull(pattern, nameof(pattern));
-
- // hack to update the writer state
- SetWriteState(JsonToken.Undefined, null);
- AddToken(new BsonRegex(pattern, options));
- }
- }
-}
diff --git a/src/Microsoft.IdentityModel.Tokens/opensource/json/ConstructorHandling.cs b/src/Microsoft.IdentityModel.Tokens/opensource/json/ConstructorHandling.cs
deleted file mode 100644
index ab6635a09b..0000000000
--- a/src/Microsoft.IdentityModel.Tokens/opensource/json/ConstructorHandling.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-#region License
-// Copyright (c) 2007 James Newton-King
-//
-// Permission is hereby granted, free of charge, to any person
-// obtaining a copy of this software and associated documentation
-// files (the "Software"), to deal in the Software without
-// restriction, including without limitation the rights to use,
-// copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following
-// conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-// OTHER DEALINGS IN THE SOFTWARE.
-#endregion
-
-namespace Microsoft.IdentityModel.Json
-{
- ///
- /// Specifies how constructors are used when initializing objects during deserialization by the .
- ///
- internal enum ConstructorHandling
- {
- ///
- /// First attempt to use the public default constructor, then fall back to a single parameterized constructor, then to the non-public default constructor.
- ///
- Default = 0,
-
- ///
- /// Json.NET will use a non-public default constructor before falling back to a parameterized constructor.
- ///
- AllowNonPublicDefaultConstructor = 1
- }
-}
diff --git a/src/Microsoft.IdentityModel.Tokens/opensource/json/Converters/BinaryConverter.cs b/src/Microsoft.IdentityModel.Tokens/opensource/json/Converters/BinaryConverter.cs
deleted file mode 100644
index 2c4dba4054..0000000000
--- a/src/Microsoft.IdentityModel.Tokens/opensource/json/Converters/BinaryConverter.cs
+++ /dev/null
@@ -1,214 +0,0 @@
-#region License
-// Copyright (c) 2007 James Newton-King
-//
-// Permission is hereby granted, free of charge, to any person
-// obtaining a copy of this software and associated documentation
-// files (the "Software"), to deal in the Software without
-// restriction, including without limitation the rights to use,
-// copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following
-// conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-// OTHER DEALINGS IN THE SOFTWARE.
-#endregion
-
-#if HAVE_LINQ || HAVE_ADO_NET
-using System;
-using System.Globalization;
-using Microsoft.IdentityModel.Json.Utilities;
-using System.Collections.Generic;
-using System.Diagnostics;
-#if HAVE_ADO_NET
-using System.Data.SqlTypes;
-#endif
-
-namespace Microsoft.IdentityModel.Json.Converters
-{
-#nullable enable
- ///
- /// Converts a binary value to and from a base 64 string value.
- ///
- internal class BinaryConverter : JsonConverter
- {
-#if HAVE_LINQ
- private const string BinaryTypeName = "System.Data.Linq.Binary";
- private const string BinaryToArrayName = "ToArray";
- private static ReflectionObject? _reflectionObject;
-#endif
-
- ///
- /// Writes the JSON representation of the object.
- ///
- /// The to write to.
- /// The value.
- /// The calling serializer.
- public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
- {
- if (value == null)
- {
- writer.WriteNull();
- return;
- }
-
- byte[] data = GetByteArray(value);
-
- writer.WriteValue(data);
- }
-
- private byte[] GetByteArray(object value)
- {
-#if HAVE_LINQ
- if (value.GetType().FullName == BinaryTypeName)
- {
- EnsureReflectionObject(value.GetType());
- MiscellaneousUtils.Assert(_reflectionObject != null);
-
- return (byte[])_reflectionObject.GetValue(value, BinaryToArrayName)!;
- }
-#endif
-#if HAVE_ADO_NET
- if (value is SqlBinary binary)
- {
- return binary.Value;
- }
-#endif
-
- throw new JsonSerializationException("Unexpected value type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
- }
-
-#if HAVE_LINQ
- private static void EnsureReflectionObject(Type t)
- {
- if (_reflectionObject == null)
- {
- _reflectionObject = ReflectionObject.Create(t, t.GetConstructor(new[] { typeof(byte[]) }), BinaryToArrayName);
- }
- }
-#endif
-
- ///
- /// Reads the JSON representation of the object.
- ///
- /// The to read from.
- /// Type of the object.
- /// The existing value of object being read.
- /// The calling serializer.
- /// The object value.
- public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
- {
- if (reader.TokenType == JsonToken.Null)
- {
- if (!ReflectionUtils.IsNullable(objectType))
- {
- throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
- }
-
- return null;
- }
-
- byte[] data;
-
- if (reader.TokenType == JsonToken.StartArray)
- {
- data = ReadByteArray(reader);
- }
- else if (reader.TokenType == JsonToken.String)
- {
- // current token is already at base64 string
- // unable to call ReadAsBytes so do it the old fashion way
- string encodedData = reader.Value!.ToString()!;
- data = Convert.FromBase64String(encodedData);
- }
- else
- {
- throw JsonSerializationException.Create(reader, "Unexpected token parsing binary. Expected String or StartArray, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
- }
-
- Type t = (ReflectionUtils.IsNullableType(objectType))
- ? Nullable.GetUnderlyingType(objectType)!
- : objectType;
-
-#if HAVE_LINQ
- if (t.FullName == BinaryTypeName)
- {
- EnsureReflectionObject(t);
- MiscellaneousUtils.Assert(_reflectionObject != null);
-
- return _reflectionObject.Creator!(data);
- }
-#endif
-
-#if HAVE_ADO_NET
- if (t == typeof(SqlBinary))
- {
- return new SqlBinary(data);
- }
-#endif
-
- throw JsonSerializationException.Create(reader, "Unexpected object type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, objectType));
- }
-
- private byte[] ReadByteArray(JsonReader reader)
- {
- List byteList = new List();
-
- while (reader.Read())
- {
- switch (reader.TokenType)
- {
- case JsonToken.Integer:
- byteList.Add(Convert.ToByte(reader.Value, CultureInfo.InvariantCulture));
- break;
- case JsonToken.EndArray:
- return byteList.ToArray();
- case JsonToken.Comment:
- // skip
- break;
- default:
- throw JsonSerializationException.Create(reader, "Unexpected token when reading bytes: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
- }
- }
-
- throw JsonSerializationException.Create(reader, "Unexpected end when reading bytes.");
- }
-
- ///
- /// Determines whether this instance can convert the specified object type.
- ///
- /// Type of the object.
- ///
- /// true if this instance can convert the specified object type; otherwise, false.
- ///
- public override bool CanConvert(Type objectType)
- {
-#if HAVE_LINQ
- if (objectType.FullName == BinaryTypeName)
- {
- return true;
- }
-#endif
-#if HAVE_ADO_NET
- if (objectType == typeof(SqlBinary) || objectType == typeof(SqlBinary?))
- {
- return true;
- }
-#endif
-
- return false;
- }
- }
-#nullable disable
-}
-
-#endif
diff --git a/src/Microsoft.IdentityModel.Tokens/opensource/json/Converters/BsonObjectIdConverter.cs b/src/Microsoft.IdentityModel.Tokens/opensource/json/Converters/BsonObjectIdConverter.cs
deleted file mode 100644
index 304fd28254..0000000000
--- a/src/Microsoft.IdentityModel.Tokens/opensource/json/Converters/BsonObjectIdConverter.cs
+++ /dev/null
@@ -1,91 +0,0 @@
-#region License
-// Copyright (c) 2007 James Newton-King
-//
-// Permission is hereby granted, free of charge, to any person
-// obtaining a copy of this software and associated documentation
-// files (the "Software"), to deal in the Software without
-// restriction, including without limitation the rights to use,
-// copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following
-// conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-// OTHER DEALINGS IN THE SOFTWARE.
-#endregion
-
-using System;
-using Microsoft.IdentityModel.Json.Bson;
-using System.Globalization;
-using Microsoft.IdentityModel.Json.Utilities;
-
-namespace Microsoft.IdentityModel.Json.Converters
-{
- ///
- /// Converts a to and from JSON and BSON.
- ///
- [Obsolete("BSON reading and writing has been moved to its own package. See https://www.nuget.org/packages/Microsoft.IdentityModel.Json.Bson for more details.")]
- internal class BsonObjectIdConverter : JsonConverter
- {
- ///
- /// Writes the JSON representation of the object.
- ///
- /// The to write to.
- /// The value.
- /// The calling serializer.
- public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
- {
- BsonObjectId objectId = (BsonObjectId)value;
-
- if (writer is BsonWriter bsonWriter)
- {
- bsonWriter.WriteObjectId(objectId.Value);
- }
- else
- {
- writer.WriteValue(objectId.Value);
- }
- }
-
- ///
- /// Reads the JSON representation of the object.
- ///
- /// The to read from.
- /// Type of the object.
- /// The existing value of object being read.
- /// The calling serializer.
- /// The object value.
- public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
- {
- if (reader.TokenType != JsonToken.Bytes)
- {
- throw new JsonSerializationException("Expected Bytes but got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
- }
-
- byte[] value = (byte[])reader.Value;
-
- return new BsonObjectId(value);
- }
-
- ///
- /// Determines whether this instance can convert the specified object type.
- ///
- /// Type of the object.
- ///
- /// true if this instance can convert the specified object type; otherwise, false.
- ///
- public override bool CanConvert(Type objectType)
- {
- return (objectType == typeof(BsonObjectId));
- }
- }
-}
diff --git a/src/Microsoft.IdentityModel.Tokens/opensource/json/Converters/CustomCreationConverter.cs b/src/Microsoft.IdentityModel.Tokens/opensource/json/Converters/CustomCreationConverter.cs
deleted file mode 100644
index 0fadd80d9f..0000000000
--- a/src/Microsoft.IdentityModel.Tokens/opensource/json/Converters/CustomCreationConverter.cs
+++ /dev/null
@@ -1,103 +0,0 @@
-#region License
-// Copyright (c) 2007 James Newton-King
-//
-// Permission is hereby granted, free of charge, to any person
-// obtaining a copy of this software and associated documentation
-// files (the "Software"), to deal in the Software without
-// restriction, including without limitation the rights to use,
-// copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following
-// conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-// OTHER DEALINGS IN THE SOFTWARE.
-#endregion
-
-using System;
-using System.Reflection;
-using Microsoft.IdentityModel.Json.Utilities;
-
-namespace Microsoft.IdentityModel.Json.Converters
-{
-#nullable enable
- ///
- /// Creates a custom object.
- ///
- /// The object type to convert.
- internal abstract class CustomCreationConverter : JsonConverter
- {
- ///
- /// Writes the JSON representation of the object.
- ///
- /// The to write to.
- /// The value.
- /// The calling serializer.
- public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
- {
- throw new NotSupportedException("CustomCreationConverter should only be used while deserializing.");
- }
-
- ///
- /// Reads the JSON representation of the object.
- ///
- /// The to read from.
- /// Type of the object.
- /// The existing value of object being read.
- /// The calling serializer.
- /// The object value.
- public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
- {
- if (reader.TokenType == JsonToken.Null)
- {
- return null;
- }
-
- T value = Create(objectType);
- if (value == null)
- {
- throw new JsonSerializationException("No object created.");
- }
-
- serializer.Populate(reader, value);
- return value;
- }
-
- ///
- /// Creates an object which will then be populated by the serializer.
- ///
- /// Type of the object.
- /// The created object.
- public abstract T Create(Type objectType);
-
- ///
- /// Determines whether this instance can convert the specified object type.
- ///
- /// Type of the object.
- ///
- /// true if this instance can convert the specified object type; otherwise, false.
- ///
- public override bool CanConvert(Type objectType)
- {
- return typeof(T).IsAssignableFrom(objectType);
- }
-
- ///
- /// Gets a value indicating whether this can write JSON.
- ///
- ///
- /// true if this can write JSON; otherwise, false.
- ///
- public override bool CanWrite => false;
- }
-#nullable disable
-}
diff --git a/src/Microsoft.IdentityModel.Tokens/opensource/json/Converters/DataSetConverter.cs b/src/Microsoft.IdentityModel.Tokens/opensource/json/Converters/DataSetConverter.cs
deleted file mode 100644
index 08c57e8f80..0000000000
--- a/src/Microsoft.IdentityModel.Tokens/opensource/json/Converters/DataSetConverter.cs
+++ /dev/null
@@ -1,127 +0,0 @@
-#region License
-// Copyright (c) 2007 James Newton-King
-//
-// Permission is hereby granted, free of charge, to any person
-// obtaining a copy of this software and associated documentation
-// files (the "Software"), to deal in the Software without
-// restriction, including without limitation the rights to use,
-// copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following
-// conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-// OTHER DEALINGS IN THE SOFTWARE.
-#endregion
-
-#if HAVE_ADO_NET
-using System;
-using System.Data;
-using Microsoft.IdentityModel.Json.Serialization;
-
-namespace Microsoft.IdentityModel.Json.Converters
-{
-#nullable enable
- ///
- /// Converts a to and from JSON.
- ///
- internal class DataSetConverter : JsonConverter
- {
- ///
- /// Writes the JSON representation of the object.
- ///
- /// The to write to.
- /// The value.
- /// The calling serializer.
- public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
- {
- if (value == null)
- {
- writer.WriteNull();
- return;
- }
-
- DataSet dataSet = (DataSet)value;
- DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver;
-
- DataTableConverter converter = new DataTableConverter();
-
- writer.WriteStartObject();
-
- foreach (DataTable table in dataSet.Tables)
- {
- writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(table.TableName) : table.TableName);
-
- converter.WriteJson(writer, table, serializer);
- }
-
- writer.WriteEndObject();
- }
-
- ///
- /// Reads the JSON representation of the object.
- ///
- /// The to read from.
- /// Type of the object.
- /// The existing value of object being read.
- /// The calling serializer.
- /// The object value.
- public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
- {
- if (reader.TokenType == JsonToken.Null)
- {
- return null;
- }
-
- // handle typed datasets
- DataSet ds = (objectType == typeof(DataSet))
- ? new DataSet()
- : (DataSet)Activator.CreateInstance(objectType)!;
-
- DataTableConverter converter = new DataTableConverter();
-
- reader.ReadAndAssert();
-
- while (reader.TokenType == JsonToken.PropertyName)
- {
- DataTable? dt = ds.Tables[(string)reader.Value!];
- bool exists = (dt != null);
-
- dt = (DataTable)converter.ReadJson(reader, typeof(DataTable), dt, serializer)!;
-
- if (!exists)
- {
- ds.Tables.Add(dt);
- }
-
- reader.ReadAndAssert();
- }
-
- return ds;
- }
-
- ///
- /// Determines whether this instance can convert the specified value type.
- ///
- /// Type of the value.
- ///
- /// true if this instance can convert the specified value type; otherwise, false.
- ///
- public override bool CanConvert(Type valueType)
- {
- return typeof(DataSet).IsAssignableFrom(valueType);
- }
- }
-#nullable disable
-}
-
-#endif
diff --git a/src/Microsoft.IdentityModel.Tokens/opensource/json/Converters/DataTableConverter.cs b/src/Microsoft.IdentityModel.Tokens/opensource/json/Converters/DataTableConverter.cs
deleted file mode 100644
index 47f0eda861..0000000000
--- a/src/Microsoft.IdentityModel.Tokens/opensource/json/Converters/DataTableConverter.cs
+++ /dev/null
@@ -1,256 +0,0 @@
-#region License
-// Copyright (c) 2007 James Newton-King
-//
-// Permission is hereby granted, free of charge, to any person
-// obtaining a copy of this software and associated documentation
-// files (the "Software"), to deal in the Software without
-// restriction, including without limitation the rights to use,
-// copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the
-// Software is furnished to do so, subject to the following
-// conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-// OTHER DEALINGS IN THE SOFTWARE.
-#endregion
-
-#if HAVE_ADO_NET
-using System.Collections;
-using System.Collections.Generic;
-using System.Globalization;
-using Microsoft.IdentityModel.Json.Utilities;
-using System;
-using System.Data;
-using Microsoft.IdentityModel.Json.Serialization;
-
-namespace Microsoft.IdentityModel.Json.Converters
-{
-#nullable enable
- ///
- /// Converts a to and from JSON.
- ///
- internal class DataTableConverter : JsonConverter
- {
- ///
- /// Writes the JSON representation of the object.
- ///
- /// The to write to.
- /// The value.
- /// The calling serializer.
- public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
- {
- if (value == null)
- {
- writer.WriteNull();
- return;
- }
-
- DataTable table = (DataTable)value;
- DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver;
-
- writer.WriteStartArray();
-
- foreach (DataRow row in table.Rows)
- {
- writer.WriteStartObject();
- foreach (DataColumn column in row.Table.Columns)
- {
- object columnValue = row[column];
-
- if (serializer.NullValueHandling == NullValueHandling.Ignore && (columnValue == null || columnValue == DBNull.Value))
- {
- continue;
- }
-
- writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(column.ColumnName) : column.ColumnName);
- serializer.Serialize(writer, columnValue);
- }
- writer.WriteEndObject();
- }
-
- writer.WriteEndArray();
- }
-
- ///
- /// Reads the JSON representation of the object.
- ///
- /// The to read from.
- /// Type of the object.
- /// The existing value of object being read.
- /// The calling serializer.
- /// The object value.
- public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
- {
- if (reader.TokenType == JsonToken.Null)
- {
- return null;
- }
-
- if (!(existingValue is DataTable dt))
- {
- // handle typed datasets
- dt = (objectType == typeof(DataTable))
- ? new DataTable()
- : (DataTable)Activator.CreateInstance(objectType)!;
- }
-
- // DataTable is inside a DataSet
- // populate the name from the property name
- if (reader.TokenType == JsonToken.PropertyName)
- {
- dt.TableName = (string)reader.Value!;
-
- reader.ReadAndAssert();
-
- if (reader.TokenType == JsonToken.Null)
- {
- return dt;
- }
- }
-
- if (reader.TokenType != JsonToken.StartArray)
- {
- throw JsonSerializationException.Create(reader, "Unexpected JSON token when reading DataTable. Expected StartArray, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
- }
-
- reader.ReadAndAssert();
-
- while (reader.TokenType != JsonToken.EndArray)
- {
- CreateRow(reader, dt, serializer);
-
- reader.ReadAndAssert();
- }
-
- return dt;
- }
-
- private static void CreateRow(JsonReader reader, DataTable dt, JsonSerializer serializer)
- {
- DataRow dr = dt.NewRow();
- reader.ReadAndAssert();
-
- while (reader.TokenType == JsonToken.PropertyName)
- {
- string columnName = (string)reader.Value!;
-
- reader.ReadAndAssert();
-
- DataColumn? column = dt.Columns[columnName];
- if (column == null)
- {
- Type columnType = GetColumnDataType(reader);
- column = new DataColumn(columnName, columnType);
- dt.Columns.Add(column);
- }
-
- if (column.DataType == typeof(DataTable))
- {
- if (reader.TokenType == JsonToken.StartArray)
- {
- reader.ReadAndAssert();
- }
-
- DataTable nestedDt = new DataTable();
-
- while (reader.TokenType != JsonToken.EndArray)
- {
- CreateRow(reader, nestedDt, serializer);
-
- reader.ReadAndAssert();
- }
-
- dr[columnName] = nestedDt;
- }
- else if (column.DataType.IsArray && column.DataType != typeof(byte[]))
- {
- if (reader.TokenType == JsonToken.StartArray)
- {
- reader.ReadAndAssert();
- }
-
- List