Skip to content

Commit

Permalink
update framework version to .net 8
Browse files Browse the repository at this point in the history
  • Loading branch information
jxnkwlp committed Jan 3, 2024
1 parent 389ffdb commit 9e44d4b
Show file tree
Hide file tree
Showing 13 changed files with 151 additions and 173 deletions.
6 changes: 5 additions & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -489,10 +489,14 @@ roslynator_refactorings.enabled = true
roslynator_compiler_diagnostic_fixes.enabled = true
tab_width = 4

#
# default|none|silent|suggestion|warning|error
dotnet_diagnostic.CA1848.severity = silent
dotnet_diagnostic.CA1305.severity = silent
dotnet_diagnostic.CA2016.severity = warning
dotnet_diagnostic.RCS1163.severity = silent
dotnet_diagnostic.RCS1228.severity = silent
dotnet_diagnostic.RCS1141.severity = silent
dotnet_diagnostic.RCS1006.severity = suggestion

[{*.har,*.jsb2,*.jsb3,*.json,.babelrc,.eslintrc,.stylelintrc,bowerrc,jest.config}]
indent_style = space
Expand Down
31 changes: 31 additions & 0 deletions common.props
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<Project>
<PropertyGroup>
<Nullable>enable</Nullable>
<AnalysisLevel>latest-minimum</AnalysisLevel>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<NoWarn>1701;1702;CS1591</NoWarn>
<LangVersion>latest</LangVersion>
<Authors>Passingwind</Authors>
<PackageProjectUrl>https://github.com/jxnkwlp/Passingwind.CommonLibs</PackageProjectUrl>
<RepositoryUrl>https://github.com/jxnkwlp/Passingwind.CommonLibs</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<PackageReadmeFile>README.md</PackageReadmeFile>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<IncludeSymbols>True</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
</PropertyGroup>

<ItemGroup>
<None Include="..\README.md">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>
9 changes: 7 additions & 2 deletions src/Authentication.ApiKey/source/ApiKeyExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
Expand All @@ -14,6 +14,7 @@ public static class ApiKeyExtensions
/// <summary>
/// Enables ApiKey authentication using the default scheme
/// </summary>
/// <typeparam name="TApiKeyProvider"></typeparam>
public static AuthenticationBuilder AddApiKey<TApiKeyProvider>(this AuthenticationBuilder builder) where TApiKeyProvider : class, IApiKeyProvider
{
return AddApiKey<TApiKeyProvider>(builder: builder, authenticationScheme: ApiKeyDefaults.AuthenticationScheme, displayName: null, configureOptions: _ => { });
Expand All @@ -22,6 +23,7 @@ public static AuthenticationBuilder AddApiKey<TApiKeyProvider>(this Authenticati
/// <summary>
/// Enables ApiKey authentication
/// </summary>
/// <typeparam name="TApiKeyProvider"></typeparam>
public static AuthenticationBuilder AddApiKey<TApiKeyProvider>(this AuthenticationBuilder builder, string authenticationScheme) where TApiKeyProvider : class, IApiKeyProvider
{
return AddApiKey<TApiKeyProvider>(builder: builder, authenticationScheme: authenticationScheme, displayName: null, configureOptions: _ => { });
Expand All @@ -30,6 +32,7 @@ public static AuthenticationBuilder AddApiKey<TApiKeyProvider>(this Authenticati
/// <summary>
/// Enables ApiKey authentication
/// </summary>
/// <typeparam name="TApiKeyProvider"></typeparam>
public static AuthenticationBuilder AddApiKey<TApiKeyProvider>(this AuthenticationBuilder builder, Action<ApiKeyOptions> configureOptions) where TApiKeyProvider : class, IApiKeyProvider
{
return AddApiKey<TApiKeyProvider>(builder: builder, authenticationScheme: ApiKeyDefaults.AuthenticationScheme, displayName: null, configureOptions: configureOptions);
Expand All @@ -38,6 +41,7 @@ public static AuthenticationBuilder AddApiKey<TApiKeyProvider>(this Authenticati
/// <summary>
/// Enables ApiKey authentication
/// </summary>
/// <typeparam name="TApiKeyProvider"></typeparam>
public static AuthenticationBuilder AddApiKey<TApiKeyProvider>(this AuthenticationBuilder builder, string authenticationScheme, Action<ApiKeyOptions> configureOptions) where TApiKeyProvider : class, IApiKeyProvider
{
return AddApiKey<TApiKeyProvider>(builder: builder, authenticationScheme: authenticationScheme, displayName: null, configureOptions: configureOptions);
Expand All @@ -46,6 +50,7 @@ public static AuthenticationBuilder AddApiKey<TApiKeyProvider>(this Authenticati
/// <summary>
/// Enables ApiKey authentication
/// </summary>
/// <typeparam name="TApiKeyProvider"></typeparam>
public static AuthenticationBuilder AddApiKey<TApiKeyProvider>(this AuthenticationBuilder builder, string authenticationScheme, string? displayName, Action<ApiKeyOptions> configureOptions) where TApiKeyProvider : class, IApiKeyProvider
{
builder.Services.TryAddTransient<IApiKeyProvider, TApiKeyProvider>();
Expand All @@ -58,4 +63,4 @@ public static AuthenticationBuilder AddApiKey<TApiKeyProvider>(this Authenticati

return builder;
}
}
}
99 changes: 60 additions & 39 deletions src/Authentication.ApiKey/source/ApiKeyHandler.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
Expand All @@ -22,11 +23,30 @@ public class ApiKeyHandler : AuthenticationHandler<ApiKeyOptions>
/// <inheritdoc />
protected new ApiKeyEvents Events { get => (ApiKeyEvents)base.Events!; set => base.Events = value; }

#if NET8_0_OR_GREATER
/// <inheritdoc />
[Obsolete("ISystemClock is obsolete, use TimeProvider on AuthenticationSchemeOptions instead.")]
public ApiKeyHandler(IOptionsMonitor<ApiKeyOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IApiKeyProvider apiKeyProvider) : base(options, logger, encoder, clock)
{
ApiKeyProvider = apiKeyProvider;
}
/// <inheritdoc />
public ApiKeyHandler(IOptionsMonitor<ApiKeyOptions> options, ILoggerFactory logger, UrlEncoder encoder, IApiKeyProvider apiKeyProvider) : base(options, logger, encoder)
{
ApiKeyProvider = apiKeyProvider;
}
#else
/// <inheritdoc />
public ApiKeyHandler(
IOptionsMonitor<ApiKeyOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock,
IApiKeyProvider apiKeyProvider) : base(options, logger, encoder, clock)
{
ApiKeyProvider = apiKeyProvider;
}
#endif

/// <inheritdoc />
protected override Task<object> CreateEventsAsync()
Expand All @@ -37,16 +57,18 @@ protected override Task<object> CreateEventsAsync()
/// <inheritdoc />
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
var messageReceivedContext = new ApiKeyMessageReceivedContext(Context, Scheme, Options);
ApiKeyMessageReceivedContext messageReceivedContext = new(Context, Scheme, Options);

await Events.MessageReceivedAsync(messageReceivedContext).ConfigureAwait(false);

if (messageReceivedContext.Result != null)
{
return messageReceivedContext.Result;
}

var request = Request;
HttpRequest request = Request;

var isApiKeyAvailable = CanHandle(request);
bool isApiKeyAvailable = CanHandle(request);

if (!isApiKeyAvailable)
{
Expand All @@ -59,38 +81,29 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
return AuthenticateResult.NoResult();
}
else
{
Logger.LogDebug("The Api Key '{token}' was found in the request.", token);
}

Logger.LogDebug("The Api Key '{token}' was found in the request.", token);

try
{
var validationResult = await ApiKeyProvider.ValidateAsync(token).ConfigureAwait(false);
ApiKeyValidationResult validationResult = await ApiKeyProvider.ValidateAsync(token).ConfigureAwait(false);

if (validationResult.Exception != null)
{
Logger.LogError(validationResult.Exception, "The API Key verification failed by {0}.", ApiKeyProvider.GetType().Name);
Logger.LogError(validationResult.Exception, "The API Key verification failed by {Name}.", ApiKeyProvider.GetType().Name);

var authenticationFailedContext = new ApiKeyAuthenticationFailedContext(Context, Scheme, Options) { Exception = validationResult.Exception };
ApiKeyAuthenticationFailedContext authenticationFailedContext = new(Context, Scheme, Options) { Exception = validationResult.Exception };

await Events.AuthenticationFailedAsync(authenticationFailedContext).ConfigureAwait(false);

if (authenticationFailedContext.Result != null)
{
return authenticationFailedContext.Result;
}

return AuthenticateResult.Fail(authenticationFailedContext.Exception);
}
else
{
Logger.LogInformation("The API Key verification successful by {0}.", ApiKeyProvider.GetType().Name);
return authenticationFailedContext.Result ?? AuthenticateResult.Fail(authenticationFailedContext.Exception);
}

var identity = validationResult.Identity;
Logger.LogInformation("The API Key verification successful by {Name}.", ApiKeyProvider.GetType().Name);

var tokenValidatedContext = new ApiKeyTokenValidatedContext(Context, Scheme, Options)
ClaimsIdentity identity = validationResult.Identity;

ApiKeyTokenValidatedContext tokenValidatedContext = new(Context, Scheme, Options)
{
Token = token,
Principal = new ClaimsPrincipal(identity),
Expand All @@ -99,7 +112,9 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
await Events.TokenValidatedAsync(tokenValidatedContext).ConfigureAwait(false);

if (tokenValidatedContext.Result != null)
{
return tokenValidatedContext.Result;
}

if (Options.SaveToken)
{
Expand All @@ -112,9 +127,9 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
}
catch (System.Exception exception)
{
Logger.LogError("Exception occurred while processing message.", exception);
Logger.LogError(exception, "Exception occurred while processing message.");

var authenticationFailedContext = new ApiKeyAuthenticationFailedContext(Context, Scheme, Options) { Exception = exception };
ApiKeyAuthenticationFailedContext authenticationFailedContext = new(Context, Scheme, Options) { Exception = exception };

await Events.AuthenticationFailedAsync(authenticationFailedContext).ConfigureAwait(false);

Expand All @@ -130,9 +145,9 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
/// <inheritdoc />
protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
{
var authResult = await HandleAuthenticateOnceSafeAsync().ConfigureAwait(false);
AuthenticateResult authResult = await HandleAuthenticateOnceSafeAsync().ConfigureAwait(false);

var eventContext = new ApiKeyChallengeContext(Context, Scheme, Options, properties)
ApiKeyChallengeContext eventContext = new(Context, Scheme, Options, properties)
{
AuthenticateFailure = authResult?.Failure
};
Expand All @@ -154,11 +169,11 @@ protected override async Task HandleChallengeAsync(AuthenticationProperties prop
{
// WWW-Authenticate: ApiKey realm="example", charset="UTF-8", in="authorization_header", in="header_or_query_params", key_name="mykey";

var builder = new StringBuilder(Options.Challenge);
StringBuilder builder = new(Options.Challenge);

if (!string.IsNullOrWhiteSpace(Options.Realm))
{
builder.Append($"realm=\"{Options.Realm}\"");
builder.Append("realm=\"").Append(Options.Realm).Append('\"');
}
if (Options.Challenge.IndexOf(' ') > 0)
{
Expand All @@ -167,9 +182,9 @@ protected override async Task HandleChallengeAsync(AuthenticationProperties prop
}
if (!string.IsNullOrEmpty(eventContext.Error))
{
builder.Append(" error=\"");
builder.Append(eventContext.Error);
builder.Append('\"');
builder.Append(" error=\"")
.Append(eventContext.Error)
.Append('\"');
}

// TODO
Expand All @@ -181,22 +196,28 @@ protected override async Task HandleChallengeAsync(AuthenticationProperties prop
/// <inheritdoc />
protected override Task HandleForbiddenAsync(AuthenticationProperties properties)
{
var forbiddenContext = new ApiKeyForbiddenContext(Context, Scheme, Options);
ApiKeyForbiddenContext forbiddenContext = new(Context, Scheme, Options);

return Events.ForbiddenAsync(forbiddenContext);
}

/// <inheritdoc />
protected virtual string? GetToken(HttpRequest request)
{
if (!string.IsNullOrWhiteSpace(Options.QueryStringName) && request.Query.TryGetValue(Options.QueryStringName, out var queryToken))
return queryToken;
if (!string.IsNullOrWhiteSpace(Options.QueryStringName) && request.Query.TryGetValue(Options.QueryStringName, out Microsoft.Extensions.Primitives.StringValues queryToken))
{
return (string?)queryToken;
}

if (!string.IsNullOrWhiteSpace(Options.HeaderName) && request.Headers.TryGetValue(Options.HeaderName, out var headerToken))
return headerToken;
if (!string.IsNullOrWhiteSpace(Options.HeaderName) && request.Headers.TryGetValue(Options.HeaderName, out Microsoft.Extensions.Primitives.StringValues headerToken))
{
return (string?)headerToken;
}

if (!string.IsNullOrWhiteSpace(Options.HeaderAuthenticationSchemeName) && request.Headers.ContainsKey(HeaderNames.Authorization) && AuthenticationHeaderValue.TryParse(request.Headers[HeaderNames.Authorization], out var headerValue))
if (!string.IsNullOrWhiteSpace(Options.HeaderAuthenticationSchemeName) && request.Headers.TryGetValue(HeaderNames.Authorization, out Microsoft.Extensions.Primitives.StringValues value) && AuthenticationHeaderValue.TryParse(value, out AuthenticationHeaderValue? headerValue))
{
return headerValue.Parameter;
}

return string.Empty;
}
Expand All @@ -206,6 +227,6 @@ protected virtual bool CanHandle(HttpRequest request)
{
return (!string.IsNullOrWhiteSpace(Options.HeaderName) && request.Headers.ContainsKey(Options.HeaderName))
|| (!string.IsNullOrWhiteSpace(Options.QueryStringName) && request.Query.ContainsKey(Options.QueryStringName))
|| (!string.IsNullOrWhiteSpace(Options.HeaderAuthenticationSchemeName) && AuthenticationHeaderValue.TryParse(request.Headers[HeaderNames.Authorization], out var headerValue) && headerValue.Scheme.Equals(Options.HeaderAuthenticationSchemeName, System.StringComparison.OrdinalIgnoreCase));
|| (!string.IsNullOrWhiteSpace(Options.HeaderAuthenticationSchemeName) && AuthenticationHeaderValue.TryParse(request.Headers[HeaderNames.Authorization], out AuthenticationHeaderValue? headerValue) && headerValue.Scheme.Equals(Options.HeaderAuthenticationSchemeName, System.StringComparison.OrdinalIgnoreCase));
}
}
}
Original file line number Diff line number Diff line change
@@ -1,48 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<Import Project="..\..\..\common.props"/>

<PropertyGroup>
<TargetFrameworks>net6;net7</TargetFrameworks>
<Nullable>enable</Nullable>
<RootNamespace>Passingwind.AspNetCore.Authentication.ApiKey</RootNamespace>
<AnalysisLevel>latest</AnalysisLevel>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<FileVersion>$(AssemblyVersion)</FileVersion>
<AssemblyVersion>0.2</AssemblyVersion>
<TargetFrameworks>net6;net7;net8</TargetFrameworks>
<RootNamespace>Passingwind.AspNetCore.Authentication.ApiKey</RootNamespace>
<Version>0.3.0</Version>
<NoWarn>1701;1702;CS1591</NoWarn>
</PropertyGroup>

<PropertyGroup>
<PackageId>Passingwind.AspNetCore.Authentication.ApiKey</PackageId>
<Title>Passingwind.AspNetCore.Authentication.ApiKey</Title>
<Authors>Passingwind</Authors>
<PackageProjectUrl>https://github.com/jxnkwlp/Passingwind.CommonLibs</PackageProjectUrl>
<RepositoryUrl>https://github.com/jxnkwlp/Passingwind.CommonLibs</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<Title>Passingwind.AspNetCore.Authentication.ApiKey</Title>
<PackageTags>authentication, ApiKey</PackageTags>
<Description>ASP.NET Core authentication handler for the ApiKey protocol</Description>
<PackageReadmeFile>README.md</PackageReadmeFile>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<IncludeSymbols>True</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<PackageVersion>0.2.0</PackageVersion>
<Description>ASP.NET Core authentication handler for the ApiKey protocol</Description>
<PackageVersion>0.3.0</PackageVersion>
</PropertyGroup>

<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>

<ItemGroup>
<None Include="..\README.md">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,7 @@

namespace Passingwind.AspNetCore.Authentication.Saml2.Configuration;

/// <summary>
///
/// </summary>
public interface IConfigurationManager
{
/// <summary>
///
/// </summary>
/// <param name="cancellationToken"></param>
Task<Saml2Configuration> GetConfigurationAsync(CancellationToken cancellationToken = default);
}
Loading

0 comments on commit 9e44d4b

Please sign in to comment.