Endpoints #13
@@ -29,6 +29,7 @@ public sealed class GetUserEndpoint : IEndpoint
|
|||||||
.Produces(StatusCodes.Status404NotFound)
|
.Produces(StatusCodes.Status404NotFound)
|
||||||
.Produces(StatusCodes.Status401Unauthorized)
|
.Produces(StatusCodes.Status401Unauthorized)
|
||||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||||
.WithTags(EndpointTags.Users);
|
.WithTags(EndpointTags.Users)
|
||||||
|
.CacheOutput();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ public class GetUsersEndpoint : IEndpoint
|
|||||||
.Produces(StatusCodes.Status404NotFound)
|
.Produces(StatusCodes.Status404NotFound)
|
||||||
.Produces(StatusCodes.Status401Unauthorized)
|
.Produces(StatusCodes.Status401Unauthorized)
|
||||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||||
.WithTags(EndpointTags.Users);
|
.WithTags(EndpointTags.Users)
|
||||||
|
.CacheOutput();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -35,6 +35,7 @@ public class SyncUserEndpoint : IEndpoint
|
|||||||
.Produces(StatusCodes.Status200OK)
|
.Produces(StatusCodes.Status200OK)
|
||||||
.Produces(StatusCodes.Status401Unauthorized)
|
.Produces(StatusCodes.Status401Unauthorized)
|
||||||
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
.Produces<Problems>(StatusCodes.Status500InternalServerError)
|
||||||
.WithTags(EndpointTags.Users);
|
.WithTags(EndpointTags.Users)
|
||||||
|
.CacheOutput();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,6 +38,54 @@ builder.Services.AddHealthChecks()
|
|||||||
.AddCheck<PostgresHealthCheck>("PostgresDatabase")
|
.AddCheck<PostgresHealthCheck>("PostgresDatabase")
|
||||||
.AddCheck("Self", () => HealthCheckResult.Healthy());
|
.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 app = builder.Build();
|
||||||
|
|
||||||
var schedulerFactory = app.Services.GetRequiredService<ISchedulerFactory>();
|
var schedulerFactory = app.Services.GetRequiredService<ISchedulerFactory>();
|
||||||
@@ -63,7 +111,7 @@ var versionGroups = new Dictionary<int, RouteGroupBuilder>
|
|||||||
{
|
{
|
||||||
{
|
{
|
||||||
1, app.MapGroup("v{version:apiVersion}").WithApiVersionSet(versionSet)
|
1, app.MapGroup("v{version:apiVersion}").WithApiVersionSet(versionSet)
|
||||||
.RequireAuthorization().AddEndpointFilter<ActiveUserFilter>()
|
.RequireAuthorization("ApiScope").AddEndpointFilter<ActiveUserFilter>()
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -86,14 +134,25 @@ var apiVersions = app.DescribeApiVersions()
|
|||||||
.ToList();
|
.ToList();
|
||||||
|
|
||||||
foreach (var description in app.DescribeApiVersions().OrderByDescending(o => o.ApiVersion.MajorVersion))
|
foreach (var description in app.DescribeApiVersions().OrderByDescending(o => o.ApiVersion.MajorVersion))
|
||||||
|
{
|
||||||
app.MapScalarApiReference($"/openapi/{description.GroupName}", (options, context) =>
|
app.MapScalarApiReference($"/openapi/{description.GroupName}", (options, context) =>
|
||||||
{
|
{
|
||||||
options.AddServer(new ScalarServer($"https://{context.Request.Host}"));
|
options.AddServer(new ScalarServer($"https://{context.Request.Host}"));
|
||||||
options.WithOpenApiRoutePattern($"/openapi/{description.GroupName}.json");
|
options.WithOpenApiRoutePattern($"/openapi/{description.GroupName}.json");
|
||||||
options.WithTheme(ScalarTheme.DeepSpace);
|
options.WithTheme(ScalarTheme.DeepSpace);
|
||||||
options.Agent = new ScalarAgentOptions { Disabled = true };
|
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";
|
var latestVersionGroup = apiVersions.FirstOrDefault()?.GroupName ?? "v1";
|
||||||
|
|
||||||
|
|||||||
@@ -23,20 +23,20 @@ public static class General
|
|||||||
|
|
||||||
public static (bool Decoded, Guid userId) GetUserId(this ClaimsPrincipal principal)
|
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);
|
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 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()
|
public static Microsoft.AspNetCore.Mvc.ProblemDetails ToProblems(this IReadOnlyList<IError> errors) => new()
|
||||||
|
|||||||
@@ -135,17 +135,25 @@ public static class Security
|
|||||||
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||||
.AddJwtBearer(options =>
|
.AddJwtBearer(options =>
|
||||||
{
|
{
|
||||||
|
options.MapInboundClaims = false;
|
||||||
options.Authority = authOptions.Authority;
|
options.Authority = authOptions.Authority;
|
||||||
options.Audience = authOptions.Audience;
|
options.Audience = authOptions.Audience;
|
||||||
|
|
||||||
options.TokenValidationParameters = new TokenValidationParameters
|
options.TokenValidationParameters = new TokenValidationParameters
|
||||||
{
|
{
|
||||||
ValidIssuer = authOptions.Authority,
|
ValidIssuer = authOptions.Authority,
|
||||||
ValidateAudience = true,
|
ValidateAudience = true,
|
||||||
ValidateIssuer = true,
|
ValidateIssuer = true,
|
||||||
|
ValidateLifetime = true,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
services.AddAuthorization();
|
services.AddAuthorizationBuilder()
|
||||||
|
.AddPolicy("ApiScope", policy =>
|
||||||
|
{
|
||||||
|
policy.RequireAuthenticatedUser();
|
||||||
|
policy.RequireClaim("scope", authOptions.Audience!);
|
||||||
|
});
|
||||||
|
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,8 +22,11 @@ public sealed class ActiveUserFilter(IdentityService identityService) : IEndpoin
|
|||||||
if (!emailDecoded)
|
if (!emailDecoded)
|
||||||
return Results.Json(new { message = "Invalid/missing user email in token." }, statusCode: StatusCodes.Status400BadRequest);
|
return Results.Json(new { message = "Invalid/missing user email in token." }, statusCode: StatusCodes.Status400BadRequest);
|
||||||
|
|
||||||
if ((await identityService.UserIsAuthorisedAsync(userId, context.HttpContext.RequestAborted)).IsFailed)
|
var path = context.HttpContext.Request.Path.Value;
|
||||||
return (object?)Results.Json(new { message = "Account approval is pending or inactive." }, statusCode: StatusCodes.Status403Forbidden);
|
|
||||||
|
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);
|
||||||
|
|
||||||
context.HttpContext.Items[UserIdItemKey] = userId;
|
context.HttpContext.Items[UserIdItemKey] = userId;
|
||||||
context.HttpContext.Items[EmailtemKey] = email;
|
context.HttpContext.Items[EmailtemKey] = email;
|
||||||
|
|||||||
@@ -26,6 +26,7 @@
|
|||||||
|
|
||||||
<!-- Shared Usings -->
|
<!-- Shared Usings -->
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<Using Include="System.IdentityModel.Tokens.Jwt" />
|
||||||
<Using Include="Asp.Versioning" />
|
<Using Include="Asp.Versioning" />
|
||||||
<Using Include="System.Security.Claims" />
|
<Using Include="System.Security.Claims" />
|
||||||
<Using Include="System.Diagnostics" />
|
<Using Include="System.Diagnostics" />
|
||||||
|
|||||||
@@ -1,4 +1,13 @@
|
|||||||
<Solution>
|
<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.Api/PostFundManagement.Api.csproj" />
|
||||||
<Project Path="PostFundManagement.Application/PostFundManagement.Application.csproj" Id="750c7754-53a7-4573-abed-5c436246a04d" />
|
<Project Path="PostFundManagement.Application/PostFundManagement.Application.csproj" Id="750c7754-53a7-4573-abed-5c436246a04d" />
|
||||||
<Project Path="PostFundManagement.Domain/PostFundManagement.Domain.csproj" />
|
<Project Path="PostFundManagement.Domain/PostFundManagement.Domain.csproj" />
|
||||||
|
|||||||
Reference in New Issue
Block a user