mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 15:11:10 +00:00
Merge pull request #68 from BinaryAlley/feature/migrate-openapi-to-scalar
Migrates the API client from Swagger to OpenApi/Scalar
This commit is contained in:
3 files changed
+72
-48
No files matched your search
+57
-46
@@ -44,34 +44,34 @@ public static class PresentationApiLayerServices
|
|||||||
});
|
});
|
||||||
|
|
||||||
// TODO: also implement account locking after a number of failed login attempts
|
// TODO: also implement account locking after a number of failed login attempts
|
||||||
services.AddRateLimiter(options =>
|
services.AddRateLimiter(rateLimiterOptions =>
|
||||||
{
|
{
|
||||||
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
|
rateLimiterOptions.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
|
||||||
options.OnRejected = async (context, cancellationToken) =>
|
rateLimiterOptions.OnRejected = async (onRejectedContext, cancellationToken) =>
|
||||||
{
|
{
|
||||||
ILogger logger = context.HttpContext.RequestServices.GetRequiredService<ILogger>();
|
ILogger logger = onRejectedContext.HttpContext.RequestServices.GetRequiredService<ILogger>();
|
||||||
|
|
||||||
string clientIp = context.HttpContext.Request.Headers["X-Forwarded-For"]
|
string clientIp = onRejectedContext.HttpContext.Request.Headers["X-Forwarded-For"]
|
||||||
.FirstOrDefault()?.Split(',')[0].Trim()
|
.FirstOrDefault()?.Split(',')[0].Trim()
|
||||||
?? context.HttpContext.Connection.RemoteIpAddress?.ToString()
|
?? onRejectedContext.HttpContext.Connection.RemoteIpAddress?.ToString()
|
||||||
?? "unknown";
|
?? "unknown";
|
||||||
Log.Warning(
|
Log.Warning(
|
||||||
"Rate limit exceeded. IP: {IpAddress}, Route: {Route}, Lease Acquired: {IsAcquired}",
|
"Rate limit exceeded. IP: {IpAddress}, Route: {Route}, Lease Acquired: {IsAcquired}",
|
||||||
clientIp,
|
clientIp,
|
||||||
context.HttpContext.Request.Path,
|
onRejectedContext.HttpContext.Request.Path,
|
||||||
context.Lease.IsAcquired); // when False, the request was rejected because it exceeded rate limits
|
onRejectedContext.Lease.IsAcquired); // when False, the request was rejected because it exceeded rate limits
|
||||||
|
|
||||||
context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
|
onRejectedContext.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
|
||||||
context.HttpContext.Response.ContentType = "application/problem+json";
|
onRejectedContext.HttpContext.Response.ContentType = "application/problem+json";
|
||||||
|
|
||||||
// set standard rate limit headers
|
// set standard rate limit headers
|
||||||
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out TimeSpan retryAfter))
|
if (onRejectedContext.Lease.TryGetMetadata(MetadataName.RetryAfter, out TimeSpan retryAfter))
|
||||||
context.HttpContext.Response.Headers.RetryAfter = ((int)retryAfter.TotalSeconds).ToString();
|
onRejectedContext.HttpContext.Response.Headers.RetryAfter = ((int)retryAfter.TotalSeconds).ToString();
|
||||||
|
|
||||||
// set custom rate limit headers
|
// set custom rate limit headers
|
||||||
context.HttpContext.Response.Headers["X-RateLimit-Limit"] = "10";
|
onRejectedContext.HttpContext.Response.Headers["X-RateLimit-Limit"] = "10";
|
||||||
context.HttpContext.Response.Headers["X-RateLimit-Remaining"] = "0";
|
onRejectedContext.HttpContext.Response.Headers["X-RateLimit-Remaining"] = "0";
|
||||||
context.HttpContext.Response.Headers["X-RateLimit-Reset"] = DateTimeOffset.UtcNow.AddMinutes(15).ToUnixTimeSeconds().ToString();
|
onRejectedContext.HttpContext.Response.Headers["X-RateLimit-Reset"] = DateTimeOffset.UtcNow.AddMinutes(15).ToUnixTimeSeconds().ToString();
|
||||||
|
|
||||||
var problem = new
|
var problem = new
|
||||||
{
|
{
|
||||||
@@ -82,9 +82,9 @@ public static class PresentationApiLayerServices
|
|||||||
retryAfter = "15"
|
retryAfter = "15"
|
||||||
};
|
};
|
||||||
|
|
||||||
await context.HttpContext.Response.WriteAsJsonAsync(problem, cancellationToken);
|
await onRejectedContext.HttpContext.Response.WriteAsJsonAsync(problem, cancellationToken);
|
||||||
};
|
};
|
||||||
options.AddPolicy("authenticationPolicy", httpContext =>
|
rateLimiterOptions.AddPolicy("authenticationPolicy", httpContext =>
|
||||||
{
|
{
|
||||||
string clientIp = httpContext.Request.Headers["X-Forwarded-For"] // first check forwarded headers, in case this is behind a reverse proxy
|
string clientIp = httpContext.Request.Headers["X-Forwarded-For"] // first check forwarded headers, in case this is behind a reverse proxy
|
||||||
.FirstOrDefault()?.Split(',')[0].Trim() // take first IP, if multiple available, to avoid IP spoofing attempts
|
.FirstOrDefault()?.Split(',')[0].Trim() // take first IP, if multiple available, to avoid IP spoofing attempts
|
||||||
@@ -104,36 +104,36 @@ public static class PresentationApiLayerServices
|
|||||||
|
|
||||||
// add authentication and specify the JWT scheme to check tokens against
|
// add authentication and specify the JWT scheme to check tokens against
|
||||||
services.AddAuthentication(defaultScheme: JwtBearerDefaults.AuthenticationScheme)
|
services.AddAuthentication(defaultScheme: JwtBearerDefaults.AuthenticationScheme)
|
||||||
.AddJwtBearer(options =>
|
.AddJwtBearer(jwtBearerOptions =>
|
||||||
{
|
{
|
||||||
options.TokenValidationParameters = new TokenValidationParameters()
|
jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters()
|
||||||
{
|
{
|
||||||
ValidateIssuer = true,
|
ValidateIssuer = true,
|
||||||
ValidateAudience = true,
|
ValidateAudience = true,
|
||||||
ValidateLifetime = true,
|
ValidateLifetime = true,
|
||||||
ValidateIssuerSigningKey = true,
|
ValidateIssuerSigningKey = true,
|
||||||
ValidIssuer = configuration["JwtSettings:Issuer"],
|
ValidIssuer = configuration.GetValue<string>("JwtSettings:Issuer"),
|
||||||
ValidAudience = configuration["JwtSettings:Audience"],
|
ValidAudience = configuration.GetValue<string>("JwtSettings:Audience"),
|
||||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtSettings:SecretKey"]!)),
|
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration.GetValue<string>("JwtSettings:SecretKey")!)),
|
||||||
};
|
};
|
||||||
|
|
||||||
options.Events = new JwtBearerEvents
|
jwtBearerOptions.Events = new JwtBearerEvents
|
||||||
{
|
{
|
||||||
OnChallenge = context => // event triggered when authentication is not successful for whatever reason
|
OnChallenge = jwtBearerChallengeContext => // event triggered when authentication is not successful for whatever reason
|
||||||
{
|
{
|
||||||
context.HandleResponse(); // prevent the default 401 response
|
jwtBearerChallengeContext.HandleResponse(); // prevent the default 401 response
|
||||||
// set the response status code to 401 Unauthorized
|
// set the response status code to 401 Unauthorized
|
||||||
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
jwtBearerChallengeContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||||
context.Response.ContentType = "application/problem+json";
|
jwtBearerChallengeContext.Response.ContentType = "application/problem+json";
|
||||||
|
|
||||||
IProblemDetailsService problemDetailsService = context.HttpContext.RequestServices.GetRequiredService<IProblemDetailsService>();
|
IProblemDetailsService problemDetailsService = jwtBearerChallengeContext.HttpContext.RequestServices.GetRequiredService<IProblemDetailsService>();
|
||||||
return context.Response.WriteAsJsonAsync(new
|
return jwtBearerChallengeContext.Response.WriteAsJsonAsync(new
|
||||||
{
|
{
|
||||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||||
status = StatusCodes.Status401Unauthorized,
|
status = StatusCodes.Status401Unauthorized,
|
||||||
title = "Unauthorized",
|
title = "Unauthorized",
|
||||||
detail = "You are not authorized",
|
detail = "You are not authorized",
|
||||||
instance = context.HttpContext.Request.Path
|
instance = jwtBearerChallengeContext.HttpContext.Request.Path
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -141,34 +141,45 @@ public static class PresentationApiLayerServices
|
|||||||
|
|
||||||
services.AddAuthorization();
|
services.AddAuthorization();
|
||||||
|
|
||||||
services.AddFastEndpoints(
|
services.AddFastEndpoints(endpointDiscoveryOptions => endpointDiscoveryOptions.Assemblies = [ typeof(Program).Assembly ]);
|
||||||
o => o.Assemblies =
|
|
||||||
[
|
services.AddOpenApi();
|
||||||
typeof(Program).Assembly
|
|
||||||
]);
|
|
||||||
services.SwaggerDocument(documentOptions =>
|
services.SwaggerDocument(documentOptions =>
|
||||||
{
|
{
|
||||||
documentOptions.SerializerSettings = s =>
|
documentOptions.EnableJWTBearerAuth = true;
|
||||||
|
documentOptions.SerializerSettings = jsonSerializerOptions =>
|
||||||
{
|
{
|
||||||
s.PropertyNamingPolicy = null;
|
jsonSerializerOptions.PropertyNamingPolicy = null;
|
||||||
s.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
|
jsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
|
||||||
};
|
};
|
||||||
documentOptions.MaxEndpointVersion = 1;
|
documentOptions.MaxEndpointVersion = 1;
|
||||||
documentOptions.MinEndpointVersion = 1;
|
documentOptions.MinEndpointVersion = 1;
|
||||||
documentOptions.DocumentSettings = s =>
|
documentOptions.DocumentSettings = aspNetCoreOpenApiDocumentGeneratorSettings =>
|
||||||
{
|
{
|
||||||
s.DocumentName = "Release 1.0";
|
aspNetCoreOpenApiDocumentGeneratorSettings.DocumentName = "v1";
|
||||||
s.Title = "Lumina API";
|
aspNetCoreOpenApiDocumentGeneratorSettings.Title = "Lumina API v1";
|
||||||
s.Version = "v1.0";
|
aspNetCoreOpenApiDocumentGeneratorSettings.Version = "v1";
|
||||||
};
|
};
|
||||||
documentOptions.RemoveEmptyRequestSchema = true;
|
documentOptions.RemoveEmptyRequestSchema = true;
|
||||||
documentOptions.ShortSchemaNames = true;
|
documentOptions.ShortSchemaNames = true;
|
||||||
});
|
}); // for an eventual next version:
|
||||||
|
//.SwaggerDocument(documentOptions =>
|
||||||
|
//{
|
||||||
|
// documentOptions.MaxEndpointVersion = 2;
|
||||||
|
// documentOptions.MinEndpointVersion = 2;
|
||||||
|
// documentOptions.DocumentSettings = aspNetCoreOpenApiDocumentGeneratorSettings =>
|
||||||
|
// {
|
||||||
|
// aspNetCoreOpenApiDocumentGeneratorSettings.DocumentName = "v2";
|
||||||
|
// aspNetCoreOpenApiDocumentGeneratorSettings.Title = "Lumina API v2";
|
||||||
|
// aspNetCoreOpenApiDocumentGeneratorSettings.Version = "v2";
|
||||||
|
// };
|
||||||
|
//});
|
||||||
|
|
||||||
services.AddCors(options =>
|
services.AddCors(corsOptions =>
|
||||||
{
|
{
|
||||||
options.AddPolicy("AllowAll",
|
corsOptions.AddPolicy("AllowAll",
|
||||||
builder => builder
|
corsPolicyBuilder => corsPolicyBuilder
|
||||||
.AllowAnyOrigin()
|
.AllowAnyOrigin()
|
||||||
.AllowAnyMethod()
|
.AllowAnyMethod()
|
||||||
.AllowAnyHeader());
|
.AllowAnyHeader());
|
||||||
|
|||||||
@@ -28,10 +28,12 @@
|
|||||||
</PackageReference>
|
</PackageReference>
|
||||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.0" />
|
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.0" />
|
||||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.0" />
|
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.0" />
|
||||||
|
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.0" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.0">
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.0">
|
||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
|
<PackageReference Include="Scalar.AspNetCore" Version="1.2.36" />
|
||||||
<PackageReference Include="Serilog" Version="4.1.1-dev-02318" />
|
<PackageReference Include="Serilog" Version="4.1.1-dev-02318" />
|
||||||
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
|
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
|
||||||
<PackageReference Include="Serilog.Enrichers.AspnetcoreHttpcontext" Version="1.1.0" />
|
<PackageReference Include="Serilog.Enrichers.AspnetcoreHttpcontext" Version="1.1.0" />
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
#region ========================================================================= USING =====================================================================================
|
||||||
using FastEndpoints;
|
using FastEndpoints;
|
||||||
using FastEndpoints.Swagger;
|
|
||||||
using Lumina.Application.Common.DependencyInjection;
|
using Lumina.Application.Common.DependencyInjection;
|
||||||
using Lumina.DataAccess.Common.DependencyInjection;
|
using Lumina.DataAccess.Common.DependencyInjection;
|
||||||
using Lumina.DataAccess.Core.UoW;
|
using Lumina.DataAccess.Core.UoW;
|
||||||
@@ -13,6 +12,7 @@ using Microsoft.EntityFrameworkCore;
|
|||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.FileProviders;
|
using Microsoft.Extensions.FileProviders;
|
||||||
|
using Scalar.AspNetCore;
|
||||||
using Serilog;
|
using Serilog;
|
||||||
using System;
|
using System;
|
||||||
using System.Diagnostics.CodeAnalysis;
|
using System.Diagnostics.CodeAnalysis;
|
||||||
@@ -106,7 +106,18 @@ public class Program
|
|||||||
config.Versioning.PrependToRoute = true;
|
config.Versioning.PrependToRoute = true;
|
||||||
config.Endpoints.ShortNames = true;
|
config.Endpoints.ShortNames = true;
|
||||||
});
|
});
|
||||||
app.UseSwaggerGen();
|
|
||||||
|
// add API documentation (OpenApi/Scalar)
|
||||||
|
app.MapOpenApi();
|
||||||
|
app.UseOpenApi(openApiDocumentMiddlewareSettings => openApiDocumentMiddlewareSettings.Path = "/openapi/{documentName}.json"); // this is needed for API versioning to work correctly with Scalar
|
||||||
|
app.MapScalarApiReference(scalarOptions =>
|
||||||
|
{
|
||||||
|
scalarOptions.WithTitle("Lumina API")
|
||||||
|
.WithTheme(ScalarTheme.BluePlanet)
|
||||||
|
.WithDefaultHttpClient(ScalarTarget.CSharp, ScalarClient.HttpClient)
|
||||||
|
//.WithFavicon() // TODO: enable when favicon is added
|
||||||
|
.WithDotNetFlag(true);
|
||||||
|
});
|
||||||
|
|
||||||
string mediaRootDirectoryPathSetting = app.Configuration.GetValue<string>("MediaSettings:RootDirectory") ?? string.Empty;
|
string mediaRootDirectoryPathSetting = app.Configuration.GetValue<string>("MediaSettings:RootDirectory") ?? string.Empty;
|
||||||
string mediaRootPath = Path.Combine(AppContext.BaseDirectory, mediaRootDirectoryPathSetting);
|
string mediaRootPath = Path.Combine(AppContext.BaseDirectory, mediaRootDirectoryPathSetting);
|
||||||
|
|||||||
Reference in new issue
Block a user