Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Add TimeProvider support to token validation #2573

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions build/common.props
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
</PropertyGroup>

<PropertyGroup>
<SuppressTfmSupportBuildWarnings>true</SuppressTfmSupportBuildWarnings>
Copy link
Author

@alexmurari alexmurari Apr 28, 2024

Choose a reason for hiding this comment

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

Suppress "Microsoft.Bcl.TimeProvider doesn't support .NET Framework 4.6.1, consider upgrading [...]" warnings. (Altough it's compatible with that framework version).

<NoWarn>$(NoWarn);SYSLIB0050</NoWarn>
<NoWarn>$(NoWarn);SYSLIB0051</NoWarn>
</PropertyGroup>
Expand Down
2 changes: 2 additions & 0 deletions build/commonTest.props
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,10 @@
</PropertyGroup>

<PropertyGroup>
<SuppressTfmSupportBuildWarnings>true</SuppressTfmSupportBuildWarnings>
Copy link
Author

Choose a reason for hiding this comment

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

Same.

<NoWarn>$(NoWarn);SYSLIB0050</NoWarn>
<NoWarn>$(NoWarn);SYSLIB0051</NoWarn>
<NoWarn>$(NoWarn);NU1701</NoWarn>
Copy link
Author

@alexmurari alexmurari Apr 28, 2024

Choose a reason for hiding this comment

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

Suppresses the "This package may not be fully compatible with your project" warning. The cause is that Microsoft.Extensions.TimeProvider.Testing package is not compatible with .NET FWK 4.6.1.

</PropertyGroup>

<ItemGroup>
Expand Down
1 change: 1 addition & 0 deletions build/dependencies.props
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
<AspNetCoreMinSupportedVersion>2.1.1</AspNetCoreMinSupportedVersion>
<MicrosoftAzureKeyVaultVersion>3.0.5</MicrosoftAzureKeyVaultVersion>
<MicrosoftAzureServicesAppAuthenticationVersion>1.0.3</MicrosoftAzureServicesAppAuthenticationVersion>
<MicrosoftBclTimeProviderVersion>8.0.1</MicrosoftBclTimeProviderVersion>
<MicrosoftCSharpVersion>4.5.0</MicrosoftCSharpVersion>
<MicrosoftSourceLinkGitHubVersion>1.0.0</MicrosoftSourceLinkGitHubVersion>
<NetStandardVersion>2.0.3</NetStandardVersion>
Expand Down
1 change: 1 addition & 0 deletions build/dependenciesTest.props
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
<PropertyGroup>
<DotNetCoreAppRuntimeVersion>2.1.30</DotNetCoreAppRuntimeVersion>
<MicrosoftAzureKeyVaultCryptographyVersion>2.0.5</MicrosoftAzureKeyVaultCryptographyVersion>
<MicrosoftExtensionsTimeProviderTestingVersion>8.4.0</MicrosoftExtensionsTimeProviderTestingVersion>
<MicrosoftNETTestSdkVersion>16.10.0</MicrosoftNETTestSdkVersion>
<NetStandardVersion>2.0.3</NetStandardVersion>
<NewtonsoftVersion>13.0.3</NewtonsoftVersion>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@
<DefineConstants>$(DefineConstants);HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_ASYNC_DISPOSABLE;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_EMIT;HAVE_REGEX_TIMEOUTS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;HAVE_INDEXOF_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_GETHASHCODE_STRING_COMPARISON;HAVE_NULLABLE_ATTRIBUTES;HAVE_DYNAMIC_CODE_COMPILED;HAS_ARRAY_EMPTY;HAVE_DATE_ONLY;$(AdditionalConstants)</DefineConstants>
</PropertyGroup>

<PropertyGroup>
<FrameworksWithoutTimeProvider>|net461|net462|net472|netstandard2.0|net6.0|</FrameworksWithoutTimeProvider>
Copy link
Author

Choose a reason for hiding this comment

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

TimeProvider is included by default in .NET 8 onwards. For every other target, we must eat the Microsoft.Bcl.TimeProvider nuget.

</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)'=='Debug'">
<DebugType>full</DebugType>
<DebugSymbols>true</DebugSymbols>
Expand Down Expand Up @@ -50,6 +54,10 @@
<PackageReference Include="System.Text.Json" Version="$(SystemTextJson)" />
</ItemGroup>

<ItemGroup Condition="$(FrameworksWithoutTimeProvider.Contains('|$(TargetFramework)|'))">
<PackageReference Include="Microsoft.Bcl.TimeProvider" Version="$(MicrosoftBclTimeProviderVersion)" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="3.0.0">
<PrivateAssets>all</PrivateAssets>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,7 @@ protected TokenValidationParameters(TokenValidationParameters other)
SaveSigninToken = other.SaveSigninToken;
SignatureValidator = other.SignatureValidator;
SignatureValidatorUsingConfiguration = other.SignatureValidatorUsingConfiguration;
TimeProvider = other.TimeProvider;
TokenDecryptionKey = other.TokenDecryptionKey;
TokenDecryptionKeyResolver = other.TokenDecryptionKeyResolver;
TokenDecryptionKeys = other.TokenDecryptionKeys;
Expand Down Expand Up @@ -381,6 +382,14 @@ public TimeSpan ClockSkew
}
}

/// <summary>
/// Gets or sets the time provider used for time validation.
/// </summary>
/// <remarks>
/// If not set, validators will fall back to using the <see cref="DateTime"/> class to obtain the current time.
/// </remarks>
public TimeProvider TimeProvider { get; set; }

/// <summary>
/// Returns a new instance of <see cref="TokenValidationParameters"/> with values copied from this object.
/// </summary>
Expand Down Expand Up @@ -539,7 +548,6 @@ public virtual ClaimsIdentity CreateClaimsIdentity(SecurityToken securityToken,
/// </remarks>
public IssuerValidator IssuerValidator { get; set; }


/// <summary>
/// Gets or sets a delegate that will be used to validate the issuer of the token.
/// </summary>
Expand Down
2 changes: 1 addition & 1 deletion src/Microsoft.IdentityModel.Tokens/ValidatorUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ internal static void ValidateLifetime(DateTime? notBefore, DateTime? expires, Se
Expires = expires
});

DateTime utcNow = DateTime.UtcNow;
DateTime utcNow = validationParameters.TimeProvider?.GetUtcNow().UtcDateTime ?? DateTime.UtcNow;
if (notBefore.HasValue && (notBefore.Value > DateTimeUtil.Add(utcNow, validationParameters.ClockSkew)))
throw LogHelper.LogExceptionMessage(new SecurityTokenNotYetValidException(LogHelper.FormatInvariant(LogMessages.IDX10222, LogHelper.MarkAsNonPII(notBefore.Value), LogHelper.MarkAsNonPII(utcNow)))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@
<PackageReference Include="Microsoft.Azure.KeyVault.Cryptography" Version="$(MicrosoftAzureKeyVaultCryptographyVersion)" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' != 'net461'">
Copy link
Author

Choose a reason for hiding this comment

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

Every test target, except .NET FWK 4.6.1 supports the Microsoft.Extensions.TimeProvider.Testing.

<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="$(MicrosoftExtensionsTimeProviderTestingVersion)" />
</ItemGroup>

<ItemGroup>
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />
</ItemGroup>
Expand Down
14 changes: 14 additions & 0 deletions test/Microsoft.IdentityModel.Tokens.Tests/ValidatorsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
#if NET462_OR_GREATER || NETCOREAPP2_1_OR_GREATER
using Microsoft.Extensions.Time.Testing;
#endif
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.TestUtils;
using Xunit;
Expand Down Expand Up @@ -366,6 +369,17 @@ public void Lifetime(DateTime? notBefore, DateTime? expires, SecurityToken secur
dataset.Add(DateTime.UtcNow + TimeSpan.FromMinutes(2), DateTime.UtcNow + TimeSpan.FromHours(1), null, new TokenValidationParameters{ ClockSkew = TimeSpan.FromMinutes(5) }, ExpectedException.NoExceptionExpected);
dataset.Add(DateTime.UtcNow - TimeSpan.FromMinutes(2), DateTime.UtcNow - TimeSpan.FromMinutes(1), null, new TokenValidationParameters{ ClockSkew = TimeSpan.FromMinutes(5) }, ExpectedException.NoExceptionExpected);

// With TimeProvider (default)
dataset.Add(DateTime.UtcNow - TimeSpan.FromHours(2), DateTime.UtcNow - TimeSpan.FromHours(1), null, new TokenValidationParameters { TimeProvider = TimeProvider.System }, ExpectedException.SecurityTokenExpiredException("IDX10223:"));
dataset.Add(DateTime.UtcNow - TimeSpan.FromHours(2), DateTime.UtcNow + TimeSpan.FromHours(1), null, new TokenValidationParameters { TimeProvider = TimeProvider.System }, ExpectedException.NoExceptionExpected);

#if NET462_OR_GREATER || NETCOREAPP2_1_OR_GREATER
// With TimeProvider (fake)
DateTime fakeUtcTime = DateTime.UtcNow.AddYears(-1);
dataset.Add(fakeUtcTime - TimeSpan.FromHours(2), fakeUtcTime - TimeSpan.FromHours(1), null, new TokenValidationParameters { TimeProvider = new FakeTimeProvider(fakeUtcTime) }, ExpectedException.SecurityTokenExpiredException("IDX10223:"));
dataset.Add(fakeUtcTime - TimeSpan.FromHours(2), fakeUtcTime + TimeSpan.FromHours(1), null, new TokenValidationParameters { TimeProvider = new FakeTimeProvider(fakeUtcTime) }, ExpectedException.NoExceptionExpected);
#endif

notBefore = EpochTime.DateTime(EpochTime.GetIntDate((DateTime.UtcNow + TimeSpan.FromMinutes(6)).ToUniversalTime()));
expires = EpochTime.DateTime(EpochTime.GetIntDate((DateTime.UtcNow + TimeSpan.FromHours(1)).ToUniversalTime()));
dataset.Add(notBefore, expires, null, new TokenValidationParameters{ ClockSkew = TimeSpan.FromMinutes(5) }, ExpectedException.SecurityTokenNotYetValidException("IDX10222:", propertiesExpected: new Dictionary<string, object> { { "NotBefore", notBefore } }));
Expand Down