Skip to content

Commit

Permalink
Update to .NET 8.0 #96
Browse files Browse the repository at this point in the history
  • Loading branch information
marcominerva committed Dec 12, 2023
1 parent e792a6a commit b6b71f8
Show file tree
Hide file tree
Showing 21 changed files with 52 additions and 133 deletions.
8 changes: 6 additions & 2 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ csharp_style_var_elsewhere = true:suggestion
csharp_style_var_for_built_in_types = true:suggestion
csharp_style_var_when_type_is_apparent = true:suggestion

# Expression-bodied members
# Expression-bodied members preferences
csharp_style_expression_bodied_accessors = true:silent
csharp_style_expression_bodied_constructors = false:silent
csharp_style_expression_bodied_indexers = true:silent
Expand Down Expand Up @@ -126,6 +126,7 @@ csharp_preferred_modifier_order = public,private,protected,internal,static,exter

# Code-block preferences
csharp_style_prefer_top_level_statements = true:suggestion
csharp_style_prefer_primary_constructors = true:suggestion
csharp_prefer_braces = true:silent
csharp_prefer_simple_using_statement = true:suggestion
csharp_style_namespace_declarations = file_scoped:suggestion
Expand All @@ -147,6 +148,7 @@ csharp_using_directive_placement = outside_namespace:suggestion

# Struct preferences
csharp_style_prefer_readonly_struct = true:suggestion
csharp_style_prefer_readonly_struct_member = true:suggestion

#### C# Formatting Rules ####

Expand All @@ -161,6 +163,8 @@ csharp_new_line_between_query_expression_clauses = true
csharp_style_allow_embedded_statements_on_same_line_experimental = false:error
csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false:error
csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true:silent
csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = true:silent
csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true:silent

# Indentation preferences
csharp_indent_block_contents = true
Expand Down Expand Up @@ -290,4 +294,4 @@ dotnet_diagnostic.IDE0058.severity = none
dotnet_diagnostic.IDE0010.severity = none

# IDE0072: Add missing cases
dotnet_diagnostic.IDE0072.severity = none
dotnet_diagnostic.IDE0072.severity = none
2 changes: 1 addition & 1 deletion samples/Controllers/ApiKeySample/ApiKeySample.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public ActionResult<User> Validate(string token, bool validateLifetime = true)
return BadRequest();
}

return new User(claimsPrincipal!.Identity!.Name);
return new User(claimsPrincipal.Identity!.Name);

Check warning on line 52 in samples/Controllers/JwtBearerSample/Controllers/AuthController.cs

View workflow job for this annotation

GitHub Actions / Analyze (csharp)

Dereference of a possibly null reference.

Check warning on line 52 in samples/Controllers/JwtBearerSample/Controllers/AuthController.cs

View workflow job for this annotation

GitHub Actions / Analyze (csharp)

Dereference of a possibly null reference.
}

[HttpPost("refresh")]
Expand Down
2 changes: 1 addition & 1 deletion samples/Controllers/JwtBearerSample/JwtBearerSample.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
Expand Down
4 changes: 2 additions & 2 deletions samples/MinimalApis/ApiKeySample/ApiKeySample.csproj
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.8" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.8" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>

Expand Down
4 changes: 2 additions & 2 deletions samples/MinimalApis/JwtBearerSample/JwtBearerSample.csproj
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.8" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>

Expand Down
5 changes: 1 addition & 4 deletions samples/MinimalApis/JwtBearerSample/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System.Security.Claims;
using JwtBearerSample.Authentication;
using JwtBearerSample.Swagger;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http.HttpResults;
using SimpleAuthentication;
Expand Down Expand Up @@ -48,8 +47,6 @@

builder.Services.AddSwaggerGen(options =>
{
options.OperationFilter<MissingSchemasOperationFilter>();

options.AddSimpleAuthentication(builder.Configuration);
});

Expand Down Expand Up @@ -104,7 +101,7 @@
return TypedResults.BadRequest();
}

return TypedResults.Ok(new User(claimsPrincipal!.Identity!.Name));
return TypedResults.Ok(new User(claimsPrincipal.Identity!.Name));

Check warning on line 104 in samples/MinimalApis/JwtBearerSample/Program.cs

View workflow job for this annotation

GitHub Actions / Analyze (csharp)

Dereference of a possibly null reference.

Check warning on line 104 in samples/MinimalApis/JwtBearerSample/Program.cs

View workflow job for this annotation

GitHub Actions / Analyze (csharp)

Dereference of a possibly null reference.
})
.WithOpenApi();

Expand Down

This file was deleted.

2 changes: 1 addition & 1 deletion src/Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
<Project>

<PropertyGroup>
<ArtifactsPath>$(MSBuildThisFileDirectory)artifacts</ArtifactsPath>
<ContinuousIntegrationBuild Condition="'$(GITHUB_ACTIONS)' == 'true'">true</ContinuousIntegrationBuild>
<DebugType>embedded</DebugType>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All"/>
<PackageReference Include="Nerdbank.GitVersioning" Version="3.6.133" PrivateAssets="All" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.IdentityModel.Tokens.Jwt;
using System.Diagnostics.CodeAnalysis;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
Expand Down Expand Up @@ -95,7 +96,7 @@ ClaimsPrincipal ValidateToken(string token)
/// <exception cref="SecurityTokenNotYetValidException"><paramref name="token"/> 'nbf' claim is &gt; DateTime.UtcNow.</exception>
/// <exception cref="SecurityTokenReplayAddFailedException"><paramref name="token"/> could not be added to the <see cref="TokenValidationParameters.TokenReplayCache"/>.</exception>
/// <exception cref="SecurityTokenReplayDetectedException"><paramref name="token"/> is found in the cache.</exception>
bool TryValidateToken(string token, out ClaimsPrincipal? claimsPrincipal)
bool TryValidateToken(string token, [NotNullWhen(true)] out ClaimsPrincipal? claimsPrincipal)
=> TryValidateToken(token, true, out claimsPrincipal);

/// <summary>
Expand All @@ -122,7 +123,7 @@ bool TryValidateToken(string token, out ClaimsPrincipal? claimsPrincipal)
/// <exception cref="SecurityTokenNotYetValidException"><paramref name="token"/> 'nbf' claim is &gt; DateTime.UtcNow.</exception>
/// <exception cref="SecurityTokenReplayAddFailedException"><paramref name="token"/> could not be added to the <see cref="TokenValidationParameters.TokenReplayCache"/>.</exception>
/// <exception cref="SecurityTokenReplayDetectedException"><paramref name="token"/> is found in the cache.</exception>
bool TryValidateToken(string token, bool validateLifetime, out ClaimsPrincipal? claimsPrincipal)
bool TryValidateToken(string token, bool validateLifetime, [NotNullWhen(true)] out ClaimsPrincipal? claimsPrincipal)
{
try
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,11 @@ namespace SimpleAuthentication.Permissions;
/// <summary>
/// Specifies that the class or method that this attribute is applied to requires the specified authorization based on permissions.
/// </summary>
/// <remarks>
/// Initializes a new instance of the <see cref="PermissionAttribute"/> class with the specified permissions.
/// </remarks>
/// <param name="permissions">The permission list to require for authorization.</param>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class PermissionAttribute : AuthorizeAttribute
public class PermissionAttribute(params string[] permissions) : AuthorizeAttribute(string.Join(",", permissions))
{
/// <summary>
/// Initializes a new instance of the <see cref="PermissionAttribute"/> class with the specified permissions.
/// </summary>
/// <param name="permissions">The permission list to require for authorization.</param>
public PermissionAttribute(params string[] permissions)
: base(string.Join(",", permissions))
{
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net6.0;net7.0</TargetFrameworks>
<TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
Expand All @@ -28,11 +28,15 @@
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'net6.0'">
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.19" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.25" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'net7.0'">
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.8" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.14" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'net8.0'">
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.0" />
</ItemGroup>

<ItemGroup>
Expand Down
11 changes: 6 additions & 5 deletions src/SimpleAuthentication/ApiKey/ApiKeyAuthenticationHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,13 @@ internal class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeySetting
{
private readonly IServiceProvider serviceProvider;

#if NET8_0_OR_GREATER
public ApiKeyAuthenticationHandler(IOptionsMonitor<ApiKeySettings> options, ILoggerFactory logger, UrlEncoder encoder, IServiceProvider serviceProvider)
: base(options, logger, encoder)
#else
public ApiKeyAuthenticationHandler(IOptionsMonitor<ApiKeySettings> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IServiceProvider serviceProvider)
: base(options, logger, encoder, clock)
#endif
{
this.serviceProvider = serviceProvider;
}
Expand All @@ -37,11 +42,7 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
if (!Options.ApiKeys.Any())
{
// There is no fixed values, so it tries to get an external service to validate the API Key.
var validator = serviceProvider.GetService<IApiKeyValidator>();
if (validator is null)
{
throw new InvalidOperationException("There isn't a default value for API Key and no custom validator has been provided");
}
var validator = serviceProvider.GetService<IApiKeyValidator>() ?? throw new InvalidOperationException("There isn't a default value for API Key and no custom validator has been provided");

var validationResult = await validator.ValidateAsync(value.ToString());
if (validationResult.Succeeded)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,13 @@ internal class BasicAuthenticationHandler : AuthenticationHandler<BasicAuthentic
{
private readonly IServiceProvider serviceProvider;

#if NET8_0_OR_GREATER
public BasicAuthenticationHandler(IOptionsMonitor<BasicAuthenticationSettings> options, ILoggerFactory logger, UrlEncoder encoder, IServiceProvider serviceProvider)
: base(options, logger, encoder)
#else
public BasicAuthenticationHandler(IOptionsMonitor<BasicAuthenticationSettings> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IServiceProvider serviceProvider)
: base(options, logger, encoder, clock)
#endif
{
this.serviceProvider = serviceProvider;
}
Expand Down Expand Up @@ -53,11 +58,7 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
if (!Options.Credentials.Any())
{
// There is no fixed values, so it tries to get an external service to validate user name and password.
var validator = serviceProvider.GetService<IBasicAuthenticationValidator>();
if (validator is null)
{
throw new InvalidOperationException("There isn't a default user name and password for authentication and no custom validator has been provided");
}
var validator = serviceProvider.GetService<IBasicAuthenticationValidator>() ?? throw new InvalidOperationException("There isn't a default user name and password for authentication and no custom validator has been provided");

var validationResult = await validator.ValidateAsync(userName, password);
if (validationResult.Succeeded)
Expand Down
9 changes: 2 additions & 7 deletions src/SimpleAuthentication/JwtBearer/JwtBearerService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,9 @@

namespace SimpleAuthentication.JwtBearer;

internal class JwtBearerService : IJwtBearerService
internal class JwtBearerService(IOptions<JwtBearerSettings> jwtBearerSettingsOptions) : IJwtBearerService
{
private readonly JwtBearerSettings jwtBearerSettings;

public JwtBearerService(IOptions<JwtBearerSettings> jwtBearerSettingsOptions)
{
jwtBearerSettings = jwtBearerSettingsOptions.Value;
}
private readonly JwtBearerSettings jwtBearerSettings = jwtBearerSettingsOptions.Value;

public string CreateToken(string userName, IList<Claim>? claims = null, string? issuer = null, string? audience = null, DateTime? absoluteExpiration = null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,8 @@

namespace SimpleAuthentication.Permissions;

internal class PermissionAuthorizationHandler : AuthorizationHandler<PermissionRequirement>
internal class PermissionAuthorizationHandler(IPermissionHandler permissionHandler) : AuthorizationHandler<PermissionRequirement>
{
private readonly IPermissionHandler permissionHandler;

public PermissionAuthorizationHandler(IPermissionHandler permissionHandler)
{
ArgumentNullException.ThrowIfNull(permissionHandler);

this.permissionHandler = permissionHandler;
}

protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
{
var isGranted = await permissionHandler.IsGrantedAsync(context.User, requirement.Permissions);
Expand Down
Loading

0 comments on commit b6b71f8

Please sign in to comment.