Skip to content

Commit

Permalink
Update sample 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 3fc8bc2 commit 777f439
Show file tree
Hide file tree
Showing 18 changed files with 120 additions and 213 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,15 @@

namespace ApiKeySample.Authentication;

public class ApplicationAuthenticationSchemeProvider : AuthenticationSchemeProvider
public class ApplicationAuthenticationSchemeProvider(IHttpContextAccessor httpContextAccessor, IOptions<AuthenticationOptions> options,
IOptions<JwtBearerSettings> jwtBearerSettingsOptions, IOptions<ApiKeySettings> apiKeySettingsOptions) : AuthenticationSchemeProvider(options)
{
private readonly IHttpContextAccessor httpContextAccessor;
private readonly JwtBearerSettings jwtBearerSettings;
private readonly ApiKeySettings apiKeySettings;

public ApplicationAuthenticationSchemeProvider(IHttpContextAccessor httpContextAccessor, IOptions<AuthenticationOptions> options,
IOptions<JwtBearerSettings> jwtBearerSettingsOptions, IOptions<ApiKeySettings> apiKeySettingsOptions)
: base(options)
{
this.httpContextAccessor = httpContextAccessor;
jwtBearerSettings = jwtBearerSettingsOptions.Value;
apiKeySettings = apiKeySettingsOptions.Value;
}
private readonly JwtBearerSettings jwtBearerSettings = jwtBearerSettingsOptions.Value;
private readonly ApiKeySettings apiKeySettings = apiKeySettingsOptions.Value;

private async Task<AuthenticationScheme?> GetRequestSchemeAsync()
{
var request = httpContextAccessor.HttpContext?.Request;
if (request is null)
{
throw new ArgumentNullException("The HTTP request cannot be retrieved.");
}
var request = (httpContextAccessor.HttpContext?.Request) ?? throw new ArgumentNullException("The HTTP request cannot be retrieved.");

// For API requests, use Jwt Bearer Authentication.
if (request.IsApiRequest())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public class MeController : ControllerBase
{
[Authorize]
[HttpGet]
[ProducesResponseType(typeof(User), StatusCodes.Status200OK)]
[ProducesResponseType<User>(StatusCodes.Status200OK)]
[ProducesDefaultResponseType]
public ActionResult<User> Get()
=> new User(User.Identity!.Name);
Expand Down
21 changes: 10 additions & 11 deletions samples/Controllers/ApiKeySample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,16 @@
// Add authentication services.
builder.Services.AddSimpleAuthentication(builder.Configuration);

//builder.Services.AddAuthorization(options =>
//{
// options.FallbackPolicy = options.DefaultPolicy = new AuthorizationPolicyBuilder()
// .AddAuthenticationSchemes(ApiKeyDefaults.AuthenticationScheme)
// .RequireAuthenticatedUser()
// .Build();

// options.AddPolicy("ApiKey", policy => policy
// .AddAuthenticationSchemes(ApiKeyDefaults.AuthenticationScheme)
// .RequireAuthenticatedUser());
//});
//builder.Services.AddAuthorizationBuilder()
// .SetDefaultPolicy(new AuthorizationPolicyBuilder()
// .AddAuthenticationSchemes(ApiKeyDefaults.AuthenticationScheme)
// .RequireAuthenticatedUser()
// .Build())
// .SetFallbackPolicy(new AuthorizationPolicyBuilder()
// .AddAuthenticationSchemes(ApiKeyDefaults.AuthenticationScheme)
// .RequireAuthenticatedUser()
// .Build())
// .AddPolicy("ApiKey", builder => builder.AddAuthenticationSchemes(ApiKeyDefaults.AuthenticationScheme).RequireAuthenticatedUser());

builder.Services.AddTransient<IApiKeyValidator, CustomApiKeyValidator>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,15 @@

namespace BasicAuthenticationSample.Authentication;

public class ApplicationAuthenticationSchemeProvider : AuthenticationSchemeProvider
public class ApplicationAuthenticationSchemeProvider(IHttpContextAccessor httpContextAccessor, IOptions<AuthenticationOptions> options,
IOptions<JwtBearerSettings> jwtBearerSettingsOptions, IOptions<ApiKeySettings> apiKeySettingsOptions) : AuthenticationSchemeProvider(options)
{
private readonly IHttpContextAccessor httpContextAccessor;
private readonly JwtBearerSettings jwtBearerSettings;
private readonly ApiKeySettings apiKeySettings;

public ApplicationAuthenticationSchemeProvider(IHttpContextAccessor httpContextAccessor, IOptions<AuthenticationOptions> options,
IOptions<JwtBearerSettings> jwtBearerSettingsOptions, IOptions<ApiKeySettings> apiKeySettingsOptions)
: base(options)
{
this.httpContextAccessor = httpContextAccessor;
jwtBearerSettings = jwtBearerSettingsOptions.Value;
apiKeySettings = apiKeySettingsOptions.Value;
}
private readonly JwtBearerSettings jwtBearerSettings = jwtBearerSettingsOptions.Value;
private readonly ApiKeySettings apiKeySettings = apiKeySettingsOptions.Value;

private async Task<AuthenticationScheme?> GetRequestSchemeAsync()
{
var request = httpContextAccessor.HttpContext?.Request;
if (request is null)
{
throw new ArgumentNullException("The HTTP request cannot be retrieved.");
}
var request = (httpContextAccessor.HttpContext?.Request) ?? throw new ArgumentNullException("The HTTP request cannot be retrieved.");

// For API requests, use Jwt Bearer Authentication.
if (request.IsApiRequest())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public class MeController : ControllerBase
{
[Authorize]
[HttpGet]
[ProducesResponseType(typeof(User), StatusCodes.Status200OK)]
[ProducesResponseType<User>(StatusCodes.Status200OK)]
[ProducesDefaultResponseType]
public ActionResult<User> Get()
=> new User(User.Identity!.Name);
Expand Down
21 changes: 10 additions & 11 deletions samples/Controllers/BasicAuthenticationSample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,16 @@
// Add authentication services.
builder.Services.AddSimpleAuthentication(builder.Configuration);

//builder.Services.AddAuthorization(options =>
//{
// options.FallbackPolicy = options.DefaultPolicy = new AuthorizationPolicyBuilder()
// .AddAuthenticationSchemes(BasicAuthenticationDefaults.AuthenticationScheme)
// .RequireAuthenticatedUser()
// .Build();

// options.AddPolicy("Basic", policy => policy
// .AddAuthenticationSchemes(BasicAuthenticationDefaults.AuthenticationScheme)
// .RequireAuthenticatedUser());
//});
//builder.Services.AddAuthorizationBuilder()
// .SetDefaultPolicy(new AuthorizationPolicyBuilder()
// .AddAuthenticationSchemes(BasicAuthenticationDefaults.AuthenticationScheme)
// .RequireAuthenticatedUser()
// .Build())
// .SetFallbackPolicy(new AuthorizationPolicyBuilder()
// .AddAuthenticationSchemes(BasicAuthenticationDefaults.AuthenticationScheme)
// .RequireAuthenticatedUser()
// .Build())
// .AddPolicy("Basic", builder => builder.AddAuthenticationSchemes(BasicAuthenticationDefaults.AuthenticationScheme).RequireAuthenticatedUser());

builder.Services.AddTransient<IBasicAuthenticationValidator, CustomBasicAuthenticationValidator>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,15 @@

namespace JwtBearerSample.Authentication;

public class ApplicationAuthenticationSchemeProvider : AuthenticationSchemeProvider
public class ApplicationAuthenticationSchemeProvider(IHttpContextAccessor httpContextAccessor, IOptions<AuthenticationOptions> options,
IOptions<JwtBearerSettings> jwtBearerSettingsOptions, IOptions<ApiKeySettings> apiKeySettingsOptions) : AuthenticationSchemeProvider(options)
{
private readonly IHttpContextAccessor httpContextAccessor;
private readonly JwtBearerSettings jwtBearerSettings;
private readonly ApiKeySettings apiKeySettings;

public ApplicationAuthenticationSchemeProvider(IHttpContextAccessor httpContextAccessor, IOptions<AuthenticationOptions> options,
IOptions<JwtBearerSettings> jwtBearerSettingsOptions, IOptions<ApiKeySettings> apiKeySettingsOptions)
: base(options)
{
this.httpContextAccessor = httpContextAccessor;
jwtBearerSettings = jwtBearerSettingsOptions.Value;
apiKeySettings = apiKeySettingsOptions.Value;
}
private readonly JwtBearerSettings jwtBearerSettings = jwtBearerSettingsOptions.Value;
private readonly ApiKeySettings apiKeySettings = apiKeySettingsOptions.Value;

private async Task<AuthenticationScheme?> GetRequestSchemeAsync()
{
var request = httpContextAccessor.HttpContext?.Request;
if (request is null)
{
throw new ArgumentNullException("The HTTP request cannot be retrieved.");
}
var request = (httpContextAccessor.HttpContext?.Request) ?? throw new ArgumentNullException("The HTTP request cannot be retrieved.");

// For API requests, use Jwt Bearer Authentication.
if (request.IsApiRequest())
Expand Down
22 changes: 7 additions & 15 deletions samples/Controllers/JwtBearerSample/Controllers/AuthController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,10 @@ namespace JwtBearerSample.Controllers;
[ApiController]
[Route("api/[controller]")]
[Produces(MediaTypeNames.Application.Json)]
public class AuthController : ControllerBase
public class AuthController(IJwtBearerService jwtBearerService) : ControllerBase
{
private readonly IJwtBearerService jwtBearerService;

public AuthController(IJwtBearerService jwtBearerService)
{
this.jwtBearerService = jwtBearerService;
}

[HttpPost("login")]
[ProducesResponseType(typeof(LoginResponse), StatusCodes.Status200OK)]
[ProducesResponseType<LoginResponse>(StatusCodes.Status200OK)]
[ProducesDefaultResponseType]
[SwaggerOperation(description: "Insert permissions in the scope property (for example: 'profile people:admin')")]
public ActionResult<LoginResponse> Login(LoginRequest loginRequest, DateTime? expiration = null)
Expand All @@ -38,22 +31,21 @@ public ActionResult<LoginResponse> Login(LoginRequest loginRequest, DateTime? ex
}

[HttpPost("validate")]
[ProducesResponseType(typeof(User), StatusCodes.Status200OK)]
[ProducesResponseType<User>(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesDefaultResponseType]
public ActionResult<User> Validate(string token, bool validateLifetime = true)
{
var isValid = jwtBearerService.TryValidateToken(token, validateLifetime, out var claimsPrincipal);
if (!isValid)
if (jwtBearerService.TryValidateToken(token, validateLifetime, out var claimsPrincipal))
{
return BadRequest();
return new User(claimsPrincipal.Identity!.Name);
}

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

[HttpPost("refresh")]
[ProducesResponseType(typeof(LoginResponse), StatusCodes.Status200OK)]
[ProducesResponseType<LoginResponse>(StatusCodes.Status200OK)]
[ProducesDefaultResponseType]
public ActionResult<LoginResponse> Refresh(string token, bool validateLifetime = true, DateTime? expiration = null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public class MeController : ControllerBase
[Authorize]
[Permission("profile")]
[HttpGet]
[ProducesResponseType(typeof(User), StatusCodes.Status200OK)]
[ProducesResponseType<User>(StatusCodes.Status200OK)]
[ProducesDefaultResponseType]
[SwaggerOperation(description: "This endpoint requires the 'profile' permission")]
public ActionResult<User> Get()
Expand Down
24 changes: 12 additions & 12 deletions samples/Controllers/JwtBearerSample/JwtBearerSample.csproj
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

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

<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.5.0" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.5.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\..\src\SimpleAuthentication\SimpleAuthentication.csproj" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\src\SimpleAuthentication\SimpleAuthentication.csproj" />
</ItemGroup>

</Project>
25 changes: 12 additions & 13 deletions samples/Controllers/JwtBearerSample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,19 @@
// Define a custom handler for permission handling.
//builder.Services.AddPermissions<CustomPermissionHandler>();

builder.Services.AddAuthorization(options =>
{
builder.Services.AddAuthorizationBuilder()
// Define permissions using a policy.
options.AddPolicy("PeopleRead", builder => builder.RequirePermission(Permissions.PeopleRead, Permissions.PeopleAdmin));

//options.FallbackPolicy = options.DefaultPolicy = new AuthorizationPolicyBuilder()
// .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
// .RequireAuthenticatedUser()
// .Build();

//options.AddPolicy("Bearer", policy => policy
// .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
// .RequireAuthenticatedUser());
});
.AddPolicy("PeopleRead", builder => builder.RequirePermission(Permissions.PeopleRead, Permissions.PeopleAdmin))
//.AddPolicy("Bearer", builder => builder.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme).RequireAuthenticatedUser())
//.SetDefaultPolicy(new AuthorizationPolicyBuilder()
// .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
// .RequireAuthenticatedUser()
// .Build())
//.SetFallbackPolicy(new AuthorizationPolicyBuilder()
// .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
// .RequireAuthenticatedUser()
// .Build())
;

// Uncomment the following line if you have multiple authentication schemes and
// you need to determine the authentication scheme at runtime (for example, you don't want to use the default authentication scheme).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,15 @@

namespace ApiKeySample.Authentication;

public class ApplicationAuthenticationSchemeProvider : AuthenticationSchemeProvider
public class ApplicationAuthenticationSchemeProvider(IHttpContextAccessor httpContextAccessor, IOptions<AuthenticationOptions> options,
IOptions<JwtBearerSettings> jwtBearerSettingsOptions, IOptions<ApiKeySettings> apiKeySettingsOptions) : AuthenticationSchemeProvider(options)
{
private readonly IHttpContextAccessor httpContextAccessor;
private readonly JwtBearerSettings jwtBearerSettings;
private readonly ApiKeySettings apiKeySettings;

public ApplicationAuthenticationSchemeProvider(IHttpContextAccessor httpContextAccessor, IOptions<AuthenticationOptions> options,
IOptions<JwtBearerSettings> jwtBearerSettingsOptions, IOptions<ApiKeySettings> apiKeySettingsOptions)
: base(options)
{
this.httpContextAccessor = httpContextAccessor;
jwtBearerSettings = jwtBearerSettingsOptions.Value;
apiKeySettings = apiKeySettingsOptions.Value;
}
private readonly JwtBearerSettings jwtBearerSettings = jwtBearerSettingsOptions.Value;
private readonly ApiKeySettings apiKeySettings = apiKeySettingsOptions.Value;

private async Task<AuthenticationScheme?> GetRequestSchemeAsync()
{
var request = httpContextAccessor.HttpContext?.Request;
if (request is null)
{
throw new ArgumentNullException("The HTTP request cannot be retrieved.");
}
var request = (httpContextAccessor.HttpContext?.Request) ?? throw new ArgumentNullException("The HTTP request cannot be retrieved.");

// For API requests, use Jwt Bearer Authentication.
if (request.IsApiRequest())
Expand Down
21 changes: 10 additions & 11 deletions samples/MinimalApis/ApiKeySample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,16 @@
// Add authentication services.
builder.Services.AddSimpleAuthentication(builder.Configuration);

//builder.Services.AddAuthorization(options =>
//{
// options.FallbackPolicy = options.DefaultPolicy = new AuthorizationPolicyBuilder()
// .AddAuthenticationSchemes(ApiKeyDefaults.AuthenticationScheme)
// .RequireAuthenticatedUser()
// .Build();

// options.AddPolicy("ApiKey", policy => policy
// .AddAuthenticationSchemes(ApiKeyDefaults.AuthenticationScheme)
// .RequireAuthenticatedUser());
//});
//builder.Services.AddAuthorizationBuilder()
// .SetDefaultPolicy(new AuthorizationPolicyBuilder()
// .AddAuthenticationSchemes(ApiKeyDefaults.AuthenticationScheme)
// .RequireAuthenticatedUser()
// .Build())
// .SetFallbackPolicy(new AuthorizationPolicyBuilder()
// .AddAuthenticationSchemes(ApiKeyDefaults.AuthenticationScheme)
// .RequireAuthenticatedUser()
// .Build())
// .AddPolicy("ApiKey", builder => builder.AddAuthenticationSchemes(ApiKeyDefaults.AuthenticationScheme).RequireAuthenticatedUser());

builder.Services.AddTransient<IApiKeyValidator, CustomApiKeyValidator>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,15 @@

namespace BasicAuthenticationSample.Authentication;

public class ApplicationAuthenticationSchemeProvider : AuthenticationSchemeProvider
public class ApplicationAuthenticationSchemeProvider(IHttpContextAccessor httpContextAccessor, IOptions<AuthenticationOptions> options,
IOptions<JwtBearerSettings> jwtBearerSettingsOptions, IOptions<ApiKeySettings> apiKeySettingsOptions) : AuthenticationSchemeProvider(options)
{
private readonly IHttpContextAccessor httpContextAccessor;
private readonly JwtBearerSettings jwtBearerSettings;
private readonly ApiKeySettings apiKeySettings;

public ApplicationAuthenticationSchemeProvider(IHttpContextAccessor httpContextAccessor, IOptions<AuthenticationOptions> options,
IOptions<JwtBearerSettings> jwtBearerSettingsOptions, IOptions<ApiKeySettings> apiKeySettingsOptions)
: base(options)
{
this.httpContextAccessor = httpContextAccessor;
jwtBearerSettings = jwtBearerSettingsOptions.Value;
apiKeySettings = apiKeySettingsOptions.Value;
}
private readonly JwtBearerSettings jwtBearerSettings = jwtBearerSettingsOptions.Value;
private readonly ApiKeySettings apiKeySettings = apiKeySettingsOptions.Value;

private async Task<AuthenticationScheme?> GetRequestSchemeAsync()
{
var request = httpContextAccessor.HttpContext?.Request;
if (request is null)
{
throw new ArgumentNullException("The HTTP request cannot be retrieved.");
}
var request = (httpContextAccessor.HttpContext?.Request) ?? throw new ArgumentNullException("The HTTP request cannot be retrieved.");

// For API requests, use Jwt Bearer Authentication.
if (request.IsApiRequest())
Expand Down
Loading

0 comments on commit 777f439

Please sign in to comment.