Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
204 lines (172 loc) · 10.9 KB
/
Copy pathProgram.cs
File metadata and controls
204 lines (172 loc) · 10.9 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
196
197
198
199
200
201
202
203
204
/*==============================================================================================================================
| Author Ignia, LLC
| Client GoldSim
| Project Website
\=============================================================================================================================*/
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.ViewComponents;
using Microsoft.AspNetCore.StaticFiles;
using GoldSim.Web;
using OnTopic.AspNetCore.Mvc;
using OnTopic.AspNetCore.Mvc.Controllers;
using OnTopic.Editor.AspNetCore;
using OnTopic.Editor.AspNetCore.Controllers;
using HeaderNames = Microsoft.Net.Http.Headers.HeaderNames;
/*==============================================================================================================================
| ENABLE SERVICES
\-----------------------------------------------------------------------------------------------------------------------------*/
var builder = WebApplication.CreateBuilder(args);
/*------------------------------------------------------------------------------------------------------------------------------
| Enable: Microsoft Identity Platform (for authentication)
>-------------------------------------------------------------------------------------------------------------------------------
| ### NOTE JJC20191122: OpenId only allows authentication against a single Azure AD tenant, or ALL Azure AD tenants. In
| order to permit authentication against both Ignia (as the development partner) and GoldSim (as the primary user) we
| need to validate the issuer. The issuer addresses can be retrieved per tenant by looking at the "issuer" attribute of
| the https://login.microsoftonline.com/{TenantId}/v2.0/.well-known/openid-configuration feed (where {TenantId} is e.g.
| "GoldSim.com").
\-----------------------------------------------------------------------------------------------------------------------------*/
builder.Services.AddAuthentication(options => {
options.DefaultAuthenticateScheme = OpenIdConnectDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddOpenIdConnect(options => {
builder.Configuration.GetSection("OpenIdConnect").Bind(options);
options.CorrelationCookie.SameSite = SameSiteMode.None;
options.SaveTokens = true;
options.TokenValidationParameters = new() {
NameClaimType = "name",
ValidIssuers = [
//Ignia users
"https://login.microsoftonline.com/10dcd9d4-80f7-47c8-ad5a-7efddcd5f868/v2.0",
//GoldSim users
"https://login.microsoftonline.com/abfc6769-97de-4dc7-8284-0ecc2fac5cfc/v2.0",
// Datacor users
"https://login.microsoftonline.com/646dd2cc-6f09-44bf-9cf6-869b33ffae59/v2.0"
]
};
})
.AddCookie();
/*------------------------------------------------------------------------------------------------------------------------------
| Enable: Output Caching
\-----------------------------------------------------------------------------------------------------------------------------*/
//builder.Services.AddResponseCaching();
/*------------------------------------------------------------------------------------------------------------------------------
| Enable: MVC, OnTopic, and OnTopic Editor
\-----------------------------------------------------------------------------------------------------------------------------*/
builder.Services.AddControllersWithViews()
//Add OnTopic support
.AddTopicSupport()
//Add OnTopic editor support
.AddTopicEditor();
/*------------------------------------------------------------------------------------------------------------------------------
| Configure: Sitemap
\-----------------------------------------------------------------------------------------------------------------------------*/
SitemapController.SkippedContentTypes.Add("Unit");
/*------------------------------------------------------------------------------------------------------------------------------
| Enable: Dependency Injection via Composition Root
\-----------------------------------------------------------------------------------------------------------------------------*/
var activator = new GoldSimActivator(builder.Configuration, builder.Environment);
builder.Services.AddSingleton<IControllerActivator>(activator);
builder.Services.AddSingleton<IViewComponentActivator>(activator);
/*------------------------------------------------------------------------------------------------------------------------------
| Enable: Application Insights
\-----------------------------------------------------------------------------------------------------------------------------*/
builder.Services.AddApplicationInsightsTelemetry(builder.Configuration);
/*==============================================================================================================================
| CONFIGURE: APPLICATION
\-----------------------------------------------------------------------------------------------------------------------------*/
var app = builder.Build();
/*------------------------------------------------------------------------------------------------------------------------------
| Configure: Environment-specific features
\-----------------------------------------------------------------------------------------------------------------------------*/
if (app.Environment.IsProduction()) {
app.UseStatusCodePagesWithReExecute("/Error/{0}/");
app.UseExceptionHandler("/Error/500/");
app.UseHsts();
}
/*------------------------------------------------------------------------------------------------------------------------------
| Configure: Static file handling with downloads and cache headers
\-----------------------------------------------------------------------------------------------------------------------------*/
var provider = new FileExtensionContentTypeProvider();
const int duration = 60*60*24*365*2; // 63072000 seconds; i.e., two years
provider.Mappings[".webmanifest"] = "application/manifest+json";
var staticFileOptions = new StaticFileOptions {
ContentTypeProvider = provider,
OnPrepareResponse = context => {
context.Context.Response.Headers[HeaderNames.CacheControl] = $"public,max-age={duration}";
}
};
app.UseStaticFiles(staticFileOptions);
/*------------------------------------------------------------------------------------------------------------------------------
| Configure: Default services
\-----------------------------------------------------------------------------------------------------------------------------*/
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseCors("default");
//app.UseResponseCaching();
/*------------------------------------------------------------------------------------------------------------------------------
| Configure: Cross-site protection for the editor
>-------------------------------------------------------------------------------------------------------------------------------
| Only accept changes through the OnTopic Editor from this site's own pages, as reported by the browser's Sec-Fetch-Site header.
| This covers every POST request, as well as Delete and SetVersion, which also accept GET requests. Requests without the header,
| such as from older browsers, are still allowed, so that a proxy that removes it can't break the editor.
\-----------------------------------------------------------------------------------------------------------------------------*/
app.Use(async (context, next) => {
//Identify changes through the editor
var action = context.GetEndpoint()?.Metadata.GetMetadata<ControllerActionDescriptor>();
var isEditorChange = action is not null &&
action.ControllerTypeInfo.AsType() == typeof(EditorController) &&
(
HttpMethods.IsPost(context.Request.Method) ||
action.ActionName is "Delete" or "SetVersion"
);
//Reject changes that didn't come from this site's own pages
var fetchSite = context.Request.Headers["Sec-Fetch-Site"].ToString();
if (isEditorChange && fetchSite is not ("" or "same-origin")) {
context.Response.StatusCode = StatusCodes.Status403Forbidden;
return;
}
//Continue processing the request
await next(context).ConfigureAwait(true);
});
/*------------------------------------------------------------------------------------------------------------------------------
| Configure: Routes
\-----------------------------------------------------------------------------------------------------------------------------*/
AppContext.SetSwitch("Microsoft.AspNetCore.Routing.UseCorrectCatchAllBehavior", true);
app.MapControllerRoute(
name : "LegacyRedirect",
pattern : "Page/{pageId}",
defaults : new {
controller = "LegacyRedirect",
action = "Redirect"
}
);
app.MapTopicEditorRoute().RequireAuthorization(); // OnTopic/{action}/{**path}
//Require authorization for the editor on every route, since e.g. the area routes below also match it
app.MapControllers().Add(endpoint => {
var isEditor = endpoint.Metadata.OfType<ControllerActionDescriptor>().Any(action =>
action.RouteValues.TryGetValue("area", out var area) && "Editor".Equals(area, StringComparison.OrdinalIgnoreCase)
);
if (isEditor) {
endpoint.Metadata.Add(new AuthorizeAttribute());
}
});
app.MapImplicitAreaControllerRoute(); // {area:exists}/{action=Index}
app.MapDefaultAreaControllerRoute(); // {area:exists}/{controller}/{action=Index}/{id?}
app.MapTopicAreaRoute(); // {area:exists}/{**path}
app.MapTopicErrors(includeStaticFiles: false); // Error/{statusCode}
app.MapDefaultControllerRoute(); // {controller=Home}/{action=Index}/{id?}
app.MapTopicRoute("Documentation").RequireAuthorization(); // Documentation/{**path}
app.MapTopicRoute(rootTopic: "Web"); // Web/{**path}
app.MapTopicRoute(rootTopic: "Error"); // Error/{**path}
app.MapTopicRedirect(); // Topic/{topicId}
app.MapControllers();
/*------------------------------------------------------------------------------------------------------------------------------
| Run application
\-----------------------------------------------------------------------------------------------------------------------------*/
app.Run();