-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathStartup.cs
More file actions
195 lines (155 loc) · 7.97 KB
/
Copy pathStartup.cs
File metadata and controls
195 lines (155 loc) · 7.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
using Ark.Reference.Core.API.JsonContext;
using Ark.Reference.Core.Application;
using Ark.Reference.Core.Common;
using Ark.Reference.Core.Common.Auth;
using Ark.Reference.Core.WebInterface.Utils;
using Ark.Tools.AspNetCore.Startup;
using Ark.Tools.AspNetCore.Swashbuckle;
using Asp.Versioning;
using Microsoft.ApplicationInsights.SnapshotCollector;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Identity.Web;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi;
using NodaTime;
using Rebus.Persistence.InMem;
using Rebus.Transport.InMem;
using Swashbuckle.AspNetCore.SwaggerUI;
namespace Ark.Reference.Core.WebInterface;
public class Startup : ArkStartupWebApi
{
public override IEnumerable<ApiVersion> Versions => ApplicationConstants.Versions.Reverse().Select(x => ApiVersionParser.Default.Parse(x));
public override OpenApiInfo MakeInfo(ApiVersion version)
=> new()
{
Title = "Core Service API",
Version = version.ToString("VVVV", CultureInfo.InvariantCulture),
};
/// <inheritdoc />
protected override void ConfigureMicrosoftOpenApi(string documentName, OpenApiOptions options)
{
base.ConfigureMicrosoftOpenApi(documentName, options);
options.AddSchemaTransformer(async (schema, context, cancellationToken) =>
{
if (context.JsonTypeInfo.Type != typeof(double?[,]))
{
return;
}
schema.Type = JsonSchemaType.Array;
schema.Items = await context.GetOrCreateSchemaAsync(typeof(double?[]), null, cancellationToken).ConfigureAwait(false);
});
options.AddOperationTransformer<MultiPartJsonOperationFilter>();
}
public Startup(IConfiguration config, IWebHostEnvironment webHostEnvironment)
: base(config, webHostEnvironment)
{
}
public override void ConfigureServices(IServiceCollection services)
{
base.ConfigureServices(services);
foreach (var version in Versions)
{
services.AddOpenApi($"v{version.ToString("VVVV", CultureInfo.InvariantCulture)}");
}
// Configure System.Text.Json source generation with Ark defaults
// Using JsonTypeInfoResolver.Combine to merge application and ProblemDetails contexts
// See: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/source-generation
// Note: JsonSerializerOptions get locked when passed to a JsonSerializerContext constructor,
// preventing the same instance from being used for multiple contexts.
// Therefore, we create separate options instances for each context.
var coreApiOptions = Application.Ex.CreateCoreApiJsonSerializerOptions();
var coreApiContext = new CoreApiJsonSerializerContext(coreApiOptions);
var problemDetailsOptions = Application.Ex.CreateCoreApiJsonSerializerOptions();
var problemDetailsContext = new Tools.AspNetCore.JsonContext.ArkProblemDetailsJsonSerializerContext(problemDetailsOptions);
// Combine source-generated contexts with minimal reflection fallback
// The fallback is required only for Hellang.Middleware.ProblemDetails internal types
// (DeveloperProblemDetailsExtensions.ErrorDetails) when IncludeExceptionDetails is enabled.
// This type is internal to the library and cannot be referenced in source generation.
// In production, exception details are typically disabled, so reflection is rarely used.
// The source-generated contexts handle 99%+ of serialization for optimal performance.
var combinedResolver = System.Text.Json.Serialization.Metadata.JsonTypeInfoResolver.Combine(
coreApiContext, // Application types - source generated (Priority 1)
problemDetailsContext, // Error types - source generated (Priority 2)
new System.Text.Json.Serialization.Metadata.DefaultJsonTypeInfoResolver()); // Fallback for middleware internals (Priority 3)
services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.TypeInfoResolver = combinedResolver;
});
services.Configure<Microsoft.AspNetCore.Mvc.JsonOptions>(options =>
{
options.JsonSerializerOptions.TypeInfoResolver = combinedResolver;
});
var integrationTestsScheme = "IntegrationTests";
var isIntegrationTests = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "IntegrationTests";
var schemes = new List<string>();
var authBuilder = services.AddAuthentication();
services.AddScoped<IClaimsTransformation, TransformEmailClaim>();
if (isIntegrationTests)
{
schemes.Add(integrationTestsScheme);
authBuilder.AddJwtBearerArkDefault(integrationTestsScheme, AuthConstants.IntegrationTestsAudience, AuthConstants.IntegrationTestsDomain, o =>
{
o.TokenValidationParameters.ValidIssuer = o.Authority;
o.Authority = null;
o.TokenValidationParameters.IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(AuthConstants.IntegrationTestsEncryptionKey));
o.TokenValidationParameters.RoleClaimType = AuthConstants.ClaimRole;
});
services.ArkConfigureSwaggerIdentityServer(AuthConstants.IntegrationTestsDomain, AuthConstants.IntegrationTestsAudience, "notneededundertest");
}
else
{
schemes.Add(JwtBearerDefaults.AuthenticationScheme);
authBuilder.AddMicrosoftIdentityWebApi(Configuration.GetRequiredSection(AuthConstants.EntraIdSchema));
services.ArkConfigureSwaggerEntraId(Configuration.GetRequiredValue<string>("EntraId:Instance")
, Configuration.GetRequiredValue<string>("EntraId:Domain")
, Configuration.GetRequiredValue<string>("EntraId:ClientId")
, Configuration.GetRequiredValue<string>("EntraId:TenantId"));
services.ConfigureSwaggerGen(c =>
{
c.IncludeXmlCommentsForAssembly<Startup>();
c.SchemaFilter<MatrixSchemaFilter>();
c.OperationFilter<MultiPartJsonOperationFilter>();
});
services.ArkConfigureSwaggerUI(c =>
{
c.MaxDisplayedTags(100);
c.DefaultModelRendering(ModelRendering.Example);
c.DefaultModelsExpandDepth(2);
c.ShowExtensions();
c.OAuthAppName("Core API");
c.ConfigObject.TryItOutEnabled = false;
});
}
var defaultPolicy = new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(schemes.ToArray())
.RequireAuthenticatedUser()
.Build();
services.AddMvcCore()
.AddMvcOptions(opt =>
{
opt.Filters.Add(new AuthorizeFilter(defaultPolicy));
opt.Conventions.Add(new ApiControllerConvention());
// add custom model binders to beginning of collection
opt.ModelBinderProviders.Insert(0, new FormDataJsonBinderProvider(opt.InputFormatters));
});
services.Configure<SnapshotCollectorConfiguration>(o =>
{
o.IsLowPrioritySnapshotUploader = false;
});
}
protected override void RegisterContainer(IServiceProvider services)
{
base.RegisterContainer(services);
var api = Configuration.BuildApiHost()
.WithContainer(Container)
.WithIClock(services.GetService<IClock>())
.WithAuthorization()
.WithRebus(Application.Host.Queue.OneWay, services.GetService<InMemNetwork>(),
services.GetService<InMemorySubscriberStore>())
;
}
}