Endpoints #13

Merged
khwezi merged 2 commits from endpoints into main 2026-09-02 16:14:34 +02:00
11 changed files with 117 additions and 34 deletions
@@ -29,6 +29,7 @@ public sealed class GetUserEndpoint : IEndpoint
.Produces(StatusCodes.Status404NotFound)
.Produces(StatusCodes.Status401Unauthorized)
.Produces<Problems>(StatusCodes.Status500InternalServerError)
.WithTags(EndpointTags.Users);
.WithTags(EndpointTags.Users)
.CacheOutput();
}
}
@@ -28,6 +28,7 @@ public class GetUsersEndpoint : IEndpoint
.Produces(StatusCodes.Status404NotFound)
.Produces(StatusCodes.Status401Unauthorized)
.Produces<Problems>(StatusCodes.Status500InternalServerError)
.WithTags(EndpointTags.Users);
.WithTags(EndpointTags.Users)
.CacheOutput();
}
}
@@ -35,6 +35,7 @@ public class SyncUserEndpoint : IEndpoint
.Produces(StatusCodes.Status200OK)
.Produces(StatusCodes.Status401Unauthorized)
.Produces<Problems>(StatusCodes.Status500InternalServerError)
.WithTags(EndpointTags.Users);
.WithTags(EndpointTags.Users)
.CacheOutput();
}
}
@@ -43,7 +43,7 @@
<ItemGroup>
<PackageReference Include="AccessTokenClient.Extensions" Version="5.1.0" />
<PackageReference Include="Asp.Versioning.Abstractions" Version="10.2.1" />
<PackageReference Include="Asp.Versioning.Http" Version="10.2.2" />
<PackageReference Include="Asp.Versioning.Http" Version="10.2.3" />
<PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="10.2.1" />
<Using Include="Asp.Versioning" />
@@ -53,7 +53,7 @@
<!-- API Documentation -->
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.11" />
<PackageReference Include="Scalar.AspNetCore" Version="2.17.1" />
<PackageReference Include="Scalar.AspNetCore" Version="2.17.2" />
<Using Include="Scalar.AspNetCore" />
<Using Include="Microsoft.OpenApi" />
+61 -2
View File
@@ -38,6 +38,54 @@ builder.Services.AddHealthChecks()
.AddCheck<PostgresHealthCheck>("PostgresDatabase")
.AddCheck("Self", () => HealthCheckResult.Healthy());
IEnumerable<string> identityScopes = ["openid", "profile", "roles", "email", "address"];
builder.Services.AddOpenApi(options =>
{
options.AddDocumentTransformer((document, context, cancellationToken) =>
{
document.Components ??= new OpenApiComponents();
document.Components?.SecuritySchemes!["OAuth2"] = new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Description = "Interactive OAuth2 flow for authentication and authorization",
Flows = new OpenApiOAuthFlows
{
AuthorizationCode = new OpenApiOAuthFlow
{
AuthorizationUrl = new Uri($"{builder.Configuration["SecuritySettings:Authority"]}/connect/authorize"),
TokenUrl = new Uri($"{builder.Configuration["SecuritySettings:Authority"]}/connect/token"),
Scopes = new Dictionary<string, string>
{
{ "openid", "OpenID Connect" },
{ "profile", "User Profile" },
{ "roles", "User Roles" },
{ "email", "User Email" },
{ "address", "User Address" },
{ builder.Configuration["SecuritySettings:Audience"]!, "PFM API Scope" }
}
}
}
};
return Task.CompletedTask;
});
options.AddOperationTransformer((operation, context, cancellationToken) =>
{
operation.Security ??= [];
var schemeReference = new OpenApiSecuritySchemeReference("OAuth2");
operation.Security.Add(new OpenApiSecurityRequirement
{
[schemeReference] = [.. identityScopes, builder.Configuration["SecuritySettings:Audience"]!]
});
return Task.CompletedTask;
});
});
var app = builder.Build();
var schedulerFactory = app.Services.GetRequiredService<ISchedulerFactory>();
@@ -63,7 +111,7 @@ var versionGroups = new Dictionary<int, RouteGroupBuilder>
{
{
1, app.MapGroup("v{version:apiVersion}").WithApiVersionSet(versionSet)
.RequireAuthorization().AddEndpointFilter<ActiveUserFilter>()
.RequireAuthorization("ApiScope").AddEndpointFilter<ActiveUserFilter>()
}
};
@@ -86,14 +134,25 @@ var apiVersions = app.DescribeApiVersions()
.ToList();
foreach (var description in app.DescribeApiVersions().OrderByDescending(o => o.ApiVersion.MajorVersion))
{
app.MapScalarApiReference($"/openapi/{description.GroupName}", (options, context) =>
{
options.AddServer(new ScalarServer($"https://{context.Request.Host}"));
options.WithOpenApiRoutePattern($"/openapi/{description.GroupName}.json");
options.WithTheme(ScalarTheme.DeepSpace);
options.Agent = new ScalarAgentOptions { Disabled = true };
options.Authentication = new ScalarAuthenticationOptions { PreferredSecuritySchemes = ["Bearer"] };
options.AddPreferredSecuritySchemes("OAuth2")
.AddOAuth2Flows("OAuth2", flow =>
{
flow.AuthorizationCode = new AuthorizationCodeFlow
{
ClientId = builder.Configuration["SecuritySettings:ClientId"]!,
Pkce = Pkce.Sha256,
SelectedScopes = [.. identityScopes, builder.Configuration["SecuritySettings:Audience"]!]
};
});
});
}
var latestVersionGroup = apiVersions.FirstOrDefault()?.GroupName ?? "v1";
@@ -23,20 +23,20 @@ public static class General
public static (bool Decoded, Guid userId) GetUserId(this ClaimsPrincipal principal)
{
var sidClaim = principal.FindFirst("sid")?.Value ?? principal.FindFirst(ClaimTypes.Sid)?.Value;
var subClaim = principal.FindFirst(JwtRegisteredClaimNames.Sub)?.Value ?? principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
var decoded = Guid.TryParse(sidClaim, out var userId);
var decoded = Guid.TryParse(subClaim, out var userId);
return (decoded, userId);
}
public static (bool Decoded, Guid email) GetUserEmail(this ClaimsPrincipal principal)
public static (bool Decoded, string email) GetUserEmail(this ClaimsPrincipal principal)
{
var emailClaim = principal.FindFirst("email")?.Value ?? principal.FindFirst(ClaimTypes.Email)?.Value;
var decoded = Guid.TryParse(emailClaim, out var email);
var decoded = !string.IsNullOrWhiteSpace(emailClaim);
return (decoded, email);
return (decoded, emailClaim!);
}
public static Microsoft.AspNetCore.Mvc.ProblemDetails ToProblems(this IReadOnlyList<IError> errors) => new()
@@ -135,17 +135,25 @@ public static class Security
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.MapInboundClaims = false;
options.Authority = authOptions.Authority;
options.Audience = authOptions.Audience;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = authOptions.Authority,
ValidateAudience = true,
ValidateIssuer = true,
ValidateLifetime = true,
};
});
services.AddAuthorization();
services.AddAuthorizationBuilder()
.AddPolicy("ApiScope", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireClaim("scope", authOptions.Audience!);
});
return services;
}
@@ -22,6 +22,9 @@ public sealed class ActiveUserFilter(IdentityService identityService) : IEndpoin
if (!emailDecoded)
return Results.Json(new { message = "Invalid/missing user email in token." }, statusCode: StatusCodes.Status400BadRequest);
var path = context.HttpContext.Request.Path.Value;
if (!string.IsNullOrWhiteSpace(path) && !path!.EndsWith("integration/sync", StringComparison.InvariantCultureIgnoreCase))
if ((await identityService.UserIsAuthorisedAsync(userId, context.HttpContext.RequestAborted)).IsFailed)
return (object?)Results.Json(new { message = "Account approval is pending or inactive." }, statusCode: StatusCodes.Status403Forbidden);
@@ -17,7 +17,7 @@
<!-- API Documentation -->
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.11" />
<PackageReference Include="Scalar.AspNetCore" Version="2.17.1" />
<PackageReference Include="Scalar.AspNetCore" Version="2.17.2" />
<Using Include="Scalar.AspNetCore" />
<Using Include="Microsoft.OpenApi" />
@@ -26,6 +26,7 @@
<!-- Shared Usings -->
<ItemGroup>
<Using Include="System.IdentityModel.Tokens.Jwt" />
<Using Include="Asp.Versioning" />
<Using Include="System.Security.Claims" />
<Using Include="System.Diagnostics" />
@@ -50,7 +50,7 @@
<ItemGroup>
<PackageReference Include="AccessTokenClient.Extensions" Version="5.1.0" />
<PackageReference Include="Asp.Versioning.Abstractions" Version="10.2.1" />
<PackageReference Include="Asp.Versioning.Http" Version="10.2.2" />
<PackageReference Include="Asp.Versioning.Http" Version="10.2.3" />
<PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="10.2.1" />
<Using Include="Asp.Versioning" />
@@ -59,7 +59,7 @@
<!-- API Documentation -->
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.11" />
<PackageReference Include="Scalar.AspNetCore" Version="2.17.1" />
<PackageReference Include="Scalar.AspNetCore" Version="2.17.2" />
<Using Include="Scalar.AspNetCore" />
<Using Include="Microsoft.OpenApi" />
@@ -69,17 +69,17 @@
<!-- Quartz Scheduler-->
<ItemGroup>
<PackageReference Include="Hashids.net" Version="1.7.0" />
<PackageReference Include="Meziantou.Analyzer" Version="3.0.177">
<PackageReference Include="Meziantou.Analyzer" Version="3.0.200">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="OpenTelemetry" Version="1.17.0" />
<PackageReference Include="Quartz" Version="3.19.1" />
<PackageReference Include="Quartz.Plugins" Version="3.19.1" />
<PackageReference Include="Quartz.Plugins.TimeZoneConverter" Version="3.19.1" />
<PackageReference Include="Quartz.Serialization.SystemTextJson" Version="3.19.1" />
<PackageReference Include="Quartz.AspNetCore" Version="3.19.1" />
<PackageReference Include="Quartz.Extensions.DependencyInjection" Version="3.19.1" />
<PackageReference Include="OpenTelemetry" Version="1.18.0" />
<PackageReference Include="Quartz" Version="3.20.0" />
<PackageReference Include="Quartz.Plugins" Version="3.20.0" />
<PackageReference Include="Quartz.Plugins.TimeZoneConverter" Version="3.20.0" />
<PackageReference Include="Quartz.Serialization.SystemTextJson" Version="3.20.0" />
<PackageReference Include="Quartz.AspNetCore" Version="3.20.0" />
<PackageReference Include="Quartz.Extensions.DependencyInjection" Version="3.20.0" />
<!-- Global Usings -->
<Using Include="Quartz" />
@@ -115,12 +115,12 @@
<!-- Open Telemetry -->
<ItemGroup>
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.17.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.17.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.17.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.17.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.17.0" />
<PackageReference Include="OpenTelemetry.Exporter.Console" Version="1.17.0" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.18.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.18.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.18.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.18.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.18.0" />
<PackageReference Include="OpenTelemetry.Exporter.Console" Version="1.18.0" />
<!-- Global Usings -->
<Using Include="OpenTelemetry.Resources" />
@@ -175,8 +175,8 @@
<!-- Amazon S3 SDK -->
<ItemGroup>
<PackageReference Include="AWSSDK.Extensions.NetCore.Setup" Version="4.0.101" />
<PackageReference Include="AWSSDK.S3" Version="4.0.102.3" />
<PackageReference Include="AWSSDK.Extensions.NetCore.Setup" Version="4.0.101.1" />
<PackageReference Include="AWSSDK.S3" Version="4.0.102.4" />
<!-- global Usings -->
<Using Include="Amazon.S3" />
+9
View File
@@ -1,4 +1,13 @@
<Solution>
<Folder Name="/Solution Items/">
<File Path=".editorconfig" />
<File Path=".gitignore" />
<File Path="docker-compose.yml" />
<File Path="Dockerfile" />
<File Path="LICENSE" />
<File Path="PostFundManagement.snk" />
<File Path="README.md" />
</Folder>
<Project Path="PostFundManagement.Api/PostFundManagement.Api.csproj" />
<Project Path="PostFundManagement.Application/PostFundManagement.Application.csproj" Id="750c7754-53a7-4573-abed-5c436246a04d" />
<Project Path="PostFundManagement.Domain/PostFundManagement.Domain.csproj" />