Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ root=true

#### Core EditorConfig Options ####

resharper_replace_auto_property_with_computed_property_highlighting = none

# Indentation and spacing
indent_size=4
indent_style=space
Expand Down Expand Up @@ -1307,8 +1309,6 @@ resharper_parameter_doesnt_make_any_sense_highlighting=warning
resharper_parameter_hides_member_highlighting=warning
resharper_parameter_only_used_for_precondition_check_global_highlighting=suggestion
resharper_parameter_only_used_for_precondition_check_local_highlighting=warning
resharper_parameter_type_can_be_enumerable_global_highlighting=hint
resharper_parameter_type_can_be_enumerable_local_highlighting=hint
resharper_parameter_value_is_not_used_highlighting=warning
resharper_partial_method_parameter_name_mismatch_highlighting=warning
resharper_partial_method_with_single_part_highlighting=warning
Expand Down Expand Up @@ -1517,8 +1517,6 @@ resharper_resource_item_not_resolved_highlighting=error
resharper_resource_not_resolved_highlighting=error
resharper_resx_not_resolved_highlighting=warning
resharper_return_from_global_scopet_with_value_highlighting=warning
resharper_return_type_can_be_enumerable_global_highlighting=hint
resharper_return_type_can_be_enumerable_local_highlighting=hint
resharper_return_value_of_pure_method_is_not_used_highlighting=warning
resharper_safe_cast_is_used_as_type_check_highlighting=suggestion
resharper_same_imports_with_different_name_highlighting=warning
Expand Down
8 changes: 4 additions & 4 deletions src/Directory.Build.targets
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<FrameworkVersion>8.0.18</FrameworkVersion>
<FrameworkVersion>8.0.19</FrameworkVersion>
</PropertyGroup>

<ItemGroup>
Expand Down Expand Up @@ -46,12 +46,12 @@
<PackageReference Update="Serilog.Sinks.File" Version="7.0.0"/>

<!--unsorted -->
<PackageReference Update="FluentAssertions" Version="8.5.0"/>
<PackageReference Update="FluentAssertions" Version="8.6.0"/>
<PackageReference Update="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="$(FrameworkVersion)"/>
<PackageReference Update="Microsoft.NET.Test.Sdk" Version="17.14.1"/>
<PackageReference Update="xunit.v3" Version="3.0.0"/>
<PackageReference Update="System.IdentityModel.Tokens.Jwt" Version="8.12.1"/>
<PackageReference Update="Microsoft.IdentityModel.Protocols.OpenIdConnect" Version="8.12.1"/>
<PackageReference Update="System.IdentityModel.Tokens.Jwt" Version="8.13.1"/>
<PackageReference Update="Microsoft.IdentityModel.Protocols.OpenIdConnect" Version="8.13.1"/>
<PackageReference Update="Newtonsoft.Json" Version="13.0.3"/>

</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,5 @@ public Task ValidateAsync(ExtensionGrantValidationContext context)
return Task.CompletedTask;
}

public string GrantType
{
get { return "custom"; }
}
public string GrantType { get; } = "custom";
}
17 changes: 5 additions & 12 deletions src/IdentityServer4/src/Extensions/IEnumerableExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;

#pragma warning disable 1591
Expand All @@ -14,19 +15,10 @@ namespace IdentityServer4.Extensions;
public static class IEnumerableExtensions
{
[DebuggerStepThrough]
public static bool IsNullOrEmpty<T>(this IEnumerable<T> list)
public static bool IsNullOrEmpty<T>([NotNullWhen(false)] this IEnumerable<T>? list)
{
if (list == null)
{
return true;
}

if (!list.Any())
{
return true;
}

return false;
if (list is null) return true;
return !list.Any();
}

public static bool HasDuplicates<T, TProp>(this IEnumerable<T> list, Func<T, TProp> selector)
Expand All @@ -39,6 +31,7 @@ public static bool HasDuplicates<T, TProp>(this IEnumerable<T> list, Func<T, TPr
return true;
}
}

return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public DistributedCacheStateDataFormatter(IHttpContextAccessor httpContext, stri
_name = name;
}

private string CacheKeyPrefix => "DistributedCacheStateDataFormatter";
private string CacheKeyPrefix { get; } = "DistributedCacheStateDataFormatter";

private IDistributedCache Cache => _httpContext.HttpContext.RequestServices.GetRequiredService<IDistributedCache>();
private IDataProtector Protector => _httpContext.HttpContext.RequestServices.GetRequiredService<IDataProtectionProvider>().CreateProtector(CacheKeyPrefix, _name);
Expand Down
34 changes: 11 additions & 23 deletions src/IdentityServer4/src/Models/GrantTypes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,41 +2,29 @@
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.


using System.Collections.Generic;

#pragma warning disable 1591

namespace IdentityServer4.Models;

public class GrantTypes
public static class GrantTypes
{
public static ICollection<string> Implicit =>
[GrantType.Implicit];
public static string[] Implicit => [GrantType.Implicit];

public static ICollection<string> ImplicitAndClientCredentials =>
[GrantType.Implicit, GrantType.ClientCredentials];
public static string[] ImplicitAndClientCredentials => [GrantType.Implicit, GrantType.ClientCredentials];

public static ICollection<string> Code =>
[GrantType.AuthorizationCode];
public static string[] Code => [GrantType.AuthorizationCode];

public static ICollection<string> CodeAndClientCredentials =>
[GrantType.AuthorizationCode, GrantType.ClientCredentials];
public static string[] CodeAndClientCredentials => [GrantType.AuthorizationCode, GrantType.ClientCredentials];

public static ICollection<string> Hybrid =>
[GrantType.Hybrid];
public static string[] Hybrid => [GrantType.Hybrid];

public static ICollection<string> HybridAndClientCredentials =>
[GrantType.Hybrid, GrantType.ClientCredentials];
public static string[] HybridAndClientCredentials => [GrantType.Hybrid, GrantType.ClientCredentials];

public static ICollection<string> ClientCredentials =>
[GrantType.ClientCredentials];
public static string[] ClientCredentials => [GrantType.ClientCredentials];

public static ICollection<string> ResourceOwnerPassword =>
[GrantType.ResourceOwnerPassword];
public static string[] ResourceOwnerPassword => [GrantType.ResourceOwnerPassword];

public static ICollection<string> ResourceOwnerPasswordAndClientCredentials =>
[GrantType.ResourceOwnerPassword, GrantType.ClientCredentials];
public static string[] ResourceOwnerPasswordAndClientCredentials => [GrantType.ResourceOwnerPassword, GrantType.ClientCredentials];

public static ICollection<string> DeviceFlow =>
[GrantType.DeviceFlow];
public static string[] DeviceFlow => [GrantType.DeviceFlow];
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,12 @@


using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using IdentityServer4.Models;
using IdentityServer4.Extensions;
using IdentityServer4.Validation;
using Microsoft.Extensions.Logging;
using IdentityServer4.Stores;
using System.Collections.Specialized;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;

Expand Down
2 changes: 1 addition & 1 deletion src/IdentityServer4/src/Test/TestUser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,5 @@ public class TestUser
/// <summary>
/// Gets or sets the claims.
/// </summary>
public ICollection<Claim> Claims { get; set; } = new HashSet<Claim>(new ClaimComparer());
public HashSet<Claim> Claims { get; set; } = new(new ClaimComparer());
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using IdentityServer4.Validation;
using System.Threading.Tasks;
using System;
using System.Linq;
using Microsoft.AspNetCore.Authentication;

namespace IdentityServer4.Test;
Expand Down Expand Up @@ -43,7 +44,7 @@ public Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
context.Result = new GrantValidationResult(
user.SubjectId ?? throw new ArgumentException("Subject ID not set", nameof(user.SubjectId)),
OidcConstants.AuthenticationMethods.Password, _clock.UtcNow.UtcDateTime,
user.Claims);
user.Claims.ToArray());
}

return Task.CompletedTask;
Expand Down
4 changes: 2 additions & 2 deletions src/IdentityServer4/src/Test/TestUserStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ public TestUser AutoProvisionUser(string provider, string userId, List<Claim> cl
}

// if no display name was provided, try to construct by first and/or last name
if (!filtered.Any(x => x.Type == JwtClaimTypes.Name))
if (filtered.All(x => x.Type != JwtClaimTypes.Name))
{
var first = filtered.FirstOrDefault(x => x.Type == JwtClaimTypes.GivenName)?.Value;
var last = filtered.FirstOrDefault(x => x.Type == JwtClaimTypes.FamilyName)?.Value;
Expand Down Expand Up @@ -146,7 +146,7 @@ public TestUser AutoProvisionUser(string provider, string userId, List<Claim> cl
Username = name,
ProviderName = provider,
ProviderSubjectId = userId,
Claims = filtered
Claims = filtered.ToHashSet()
};

// add user to in-memory store
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
using IdentityServer4.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace IdentityServer4.Validation;
Expand All @@ -17,7 +17,8 @@ namespace IdentityServer4.Validation;
public class ExtensionGrantValidator
{
private readonly ILogger _logger;
private readonly IEnumerable<IExtensionGrantValidator> _validators;
private readonly FrozenSet<string> _availableGrantTypes;
private readonly FrozenDictionary<string, IExtensionGrantValidator> _validators;

/// <summary>
/// Initializes a new instance of the <see cref="ExtensionGrantValidator"/> class.
Expand All @@ -26,26 +27,17 @@ public class ExtensionGrantValidator
/// <param name="logger">The logger.</param>
public ExtensionGrantValidator(IEnumerable<IExtensionGrantValidator> validators, ILogger<ExtensionGrantValidator> logger)
{
if (validators == null)
{
_validators = [];
}
else
{
_validators = validators;
}

_logger = logger;

_validators = validators.ToFrozenDictionary(x => x.GrantType);
_availableGrantTypes = _validators.Keys.ToFrozenSet();
}

/// <summary>
/// Gets the available grant types.
/// </summary>
/// <returns></returns>
public IEnumerable<string> GetAvailableGrantTypes()
{
return _validators.Select(v => v.GrantType);
}
public FrozenSet<string> GetAvailableGrantTypes() => _availableGrantTypes;

/// <summary>
/// Validates the request.
Expand All @@ -54,29 +46,27 @@ public IEnumerable<string> GetAvailableGrantTypes()
/// <returns></returns>
public async Task<GrantValidationResult> ValidateAsync(ValidatedTokenRequest request)
{
var validator = _validators.FirstOrDefault(v => v.GrantType.Equals(request.GrantType, StringComparison.Ordinal));

if (validator == null)
if (!_validators.TryGetValue(request.GrantType, out var validator))
Comment thread
juk-777 marked this conversation as resolved.
{
_logger.LogError("No validator found for grant type");
return new GrantValidationResult(TokenRequestErrors.UnsupportedGrantType);
}

try
{
_logger.LogTrace("Calling into custom grant validator: {type}", validator.GetType().FullName);
_logger.LogTrace("Calling into custom grant validator: {Type}", validator.GetType().FullName);

var context = new ExtensionGrantValidationContext
{
Request = request
};

await validator.ValidateAsync(context);
return context.Result;
}
catch (Exception e)
{
_logger.LogError(1, e, "Grant validation error: {message}", e.Message);
_logger.LogError(1, e, "Grant validation error: {Message}", e.Message);
return new GrantValidationResult(TokenRequestErrors.InvalidGrant);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -589,7 +589,7 @@ private async Task<TokenRequestValidationResult> ValidateExtensionGrantRequestAs
/////////////////////////////////////////////
// check if a validator is registered for the grant type
/////////////////////////////////////////////
if (!_extensionGrantValidator.GetAvailableGrantTypes().Contains(_validatedRequest.GrantType, StringComparer.Ordinal))
if (!_extensionGrantValidator.GetAvailableGrantTypes().Contains(_validatedRequest.GrantType))
Comment thread
juk-777 marked this conversation as resolved.
{
LogError("No validator is registered for the grant type", new { grantType = _validatedRequest.GrantType });
return Invalid(OidcConstants.TokenErrors.UnsupportedGrantType);
Expand Down
Loading